javatips.net counter

Java Examples for com.google.gwt.core.client.JavaScriptObject

The following java examples will help you to understand the usage of com.google.gwt.core.client.JavaScriptObject. These source code samples are taken from different open source projects.

Example 1
Project: platypus-master  File: ButtonGroup.java View source code
@Override
public void onSelection(SelectionEvent<UIObject> event) {
    if (onItemSelected != null) {
        try {
            JavaScriptObject jsItem = event.getSelectedItem() instanceof HasPublished ? ((HasPublished) event.getSelectedItem()).getPublished() : null;
            Utils.executeScriptEventVoid(published, onItemSelected, EventsPublisher.publishItemEvent(published, jsItem));
        } catch (Exception e) {
            Logger.getLogger(EventsExecutor.class.getName()).log(Level.SEVERE, null, e);
        }
    }
}
Example 2
Project: google-web-toolkit-svnmirror-master  File: JsoEval.java View source code
/**
   * A convenience form of 
   * [email protected] #call(Class, Object, String, Class[], Object...)} for use directly
   * by users in a debugger. This method guesses at the types of the method
   * based on the values of [email protected] args}.
   */
public static Object callEx(Class klass, Object obj, String methodName, Object... args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
    if (args == null) {
        // A single-argument varargs null can come in unboxed  
        args = new Object[] { null };
    }
    if (obj != null) {
        if (!obj.getClass().getName().equals(JSO_IMPL_CLASS)) {
            throw new RuntimeException(obj + " is not a JavaScriptObject.");
        }
    }
    // First check java.lang.Object methods for exact matches
    Method[] methods = Object.class.getMethods();
    nextMethod: for (Method m : methods) {
        if (m.getName().equals(methodName)) {
            Class[] types = m.getParameterTypes();
            if (types.length != args.length) {
                continue;
            }
            for (int i = 0, j = 0; i < args.length; ++i, ++j) {
                if (!isAssignable(types[i], args[j])) {
                    continue nextMethod;
                }
            }
            return m.invoke(obj, args);
        }
    }
    ClassLoader ccl = getCompilingClassLoader(klass, obj);
    boolean isJso = isJso(ccl, klass);
    boolean isStaticifiedDispatch = isJso && obj != null;
    int actualNumArgs = isStaticifiedDispatch ? args.length + 1 : args.length;
    ArrayList<Method> matchingMethods = new ArrayList<Method>(Arrays.asList(isJso ? getSisterJsoImpl(klass, ccl).getMethods() : getJsoImplClass(ccl).getMethods()));
    String mangledMethodName = mangleMethod(klass, methodName, isJso, isStaticifiedDispatch);
    // Filter the methods in multiple passes to give better error messages.
    for (Iterator<Method> it = matchingMethods.iterator(); it.hasNext(); ) {
        Method m = it.next();
        if (!m.getName().equalsIgnoreCase(mangledMethodName)) {
            it.remove();
        }
    }
    if (matchingMethods.isEmpty()) {
        throw new RuntimeException("No methods by the name, " + methodName + ", could be found in " + klass);
    }
    ArrayList<Method> candidates = new ArrayList<Method>(matchingMethods);
    for (Iterator<Method> it = matchingMethods.iterator(); it.hasNext(); ) {
        Method m = it.next();
        if (m.getParameterTypes().length != actualNumArgs) {
            it.remove();
        }
    }
    if (matchingMethods.isEmpty()) {
        throw new RuntimeException("No methods by the name, " + methodName + ", in " + klass + " accept " + args.length + " parameters. Candidates are:\n" + candidates);
    }
    candidates = new ArrayList<Method>(matchingMethods);
    nextMethod: for (Iterator<Method> it = matchingMethods.iterator(); it.hasNext(); ) {
        Method m = it.next();
        Class[] methodTypes = m.getParameterTypes();
        for (int i = isStaticifiedDispatch ? 1 : 0, j = 0; i < methodTypes.length; ++i, ++j) {
            if (!isAssignable(methodTypes[i], args[j])) {
                it.remove();
                continue nextMethod;
            }
        }
    }
    if (matchingMethods.isEmpty()) {
        throw new RuntimeException("No methods accepting " + Arrays.asList(args) + " were found for, " + methodName + ", in " + klass + ". Candidates:\n" + candidates);
    }
    candidates = new ArrayList<Method>(matchingMethods);
    if (matchingMethods.size() > 1) {
        // methods by same name but different case.
        for (Iterator<Method> it = matchingMethods.iterator(); it.hasNext(); ) {
            Method m = it.next();
            if (!m.getName().equals(mangledMethodName)) {
                it.remove();
            }
        }
    }
    if (matchingMethods.isEmpty()) {
        throw new RuntimeException("Multiple methods with a case-insensitive match were found for, " + methodName + ", in " + klass + ". Candidates:\n" + candidates);
    }
    if (matchingMethods.size() > 1) {
        throw new RuntimeException("Found more than one matching method. Please specify the types of the parameters. " + "Candidates:\n" + matchingMethods);
    }
    return invoke(klass, obj, matchingMethods.get(0), args);
}
Example 3
Project: gwt-sandbox-master  File: JsoEval.java View source code
/**
   * A convenience form of 
   * [email protected] #call(Class, Object, String, Class[], Object...)} for use directly
   * by users in a debugger. This method guesses at the types of the method
   * based on the values of [email protected] args}.
   */
public static Object callEx(Class klass, Object obj, String methodName, Object... args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
    if (args == null) {
        // A single-argument varargs null can come in unboxed  
        args = new Object[] { null };
    }
    if (obj != null) {
        if (!obj.getClass().getName().equals(JSO_IMPL_CLASS)) {
            throw new RuntimeException(obj + " is not a JavaScriptObject.");
        }
    }
    // First check java.lang.Object methods for exact matches
    Method[] methods = Object.class.getMethods();
    nextMethod: for (Method m : methods) {
        if (m.getName().equals(methodName)) {
            Class[] types = m.getParameterTypes();
            if (types.length != args.length) {
                continue;
            }
            for (int i = 0, j = 0; i < args.length; ++i, ++j) {
                if (!isAssignable(types[i], args[j])) {
                    continue nextMethod;
                }
            }
            return m.invoke(obj, args);
        }
    }
    ClassLoader ccl = getCompilingClassLoader(klass, obj);
    boolean isJso = isJso(ccl, klass);
    boolean isStaticifiedDispatch = isJso && obj != null;
    int actualNumArgs = isStaticifiedDispatch ? args.length + 1 : args.length;
    ArrayList<Method> matchingMethods = new ArrayList<Method>(Arrays.asList(isJso ? getSisterJsoImpl(klass, ccl).getMethods() : getJsoImplClass(ccl).getMethods()));
    String mangledMethodName = mangleMethod(klass, methodName, isJso, isStaticifiedDispatch);
    // Filter the methods in multiple passes to give better error messages.
    for (Iterator<Method> it = matchingMethods.iterator(); it.hasNext(); ) {
        Method m = it.next();
        if (!m.getName().equalsIgnoreCase(mangledMethodName)) {
            it.remove();
        }
    }
    if (matchingMethods.isEmpty()) {
        throw new RuntimeException("No methods by the name, " + methodName + ", could be found in " + klass);
    }
    ArrayList<Method> candidates = new ArrayList<Method>(matchingMethods);
    for (Iterator<Method> it = matchingMethods.iterator(); it.hasNext(); ) {
        Method m = it.next();
        if (m.getParameterTypes().length != actualNumArgs) {
            it.remove();
        }
    }
    if (matchingMethods.isEmpty()) {
        throw new RuntimeException("No methods by the name, " + methodName + ", in " + klass + " accept " + args.length + " parameters. Candidates are:\n" + candidates);
    }
    candidates = new ArrayList<Method>(matchingMethods);
    nextMethod: for (Iterator<Method> it = matchingMethods.iterator(); it.hasNext(); ) {
        Method m = it.next();
        Class[] methodTypes = m.getParameterTypes();
        for (int i = isStaticifiedDispatch ? 1 : 0, j = 0; i < methodTypes.length; ++i, ++j) {
            if (!isAssignable(methodTypes[i], args[j])) {
                it.remove();
                continue nextMethod;
            }
        }
    }
    if (matchingMethods.isEmpty()) {
        throw new RuntimeException("No methods accepting " + Arrays.asList(args) + " were found for, " + methodName + ", in " + klass + ". Candidates:\n" + candidates);
    }
    candidates = new ArrayList<Method>(matchingMethods);
    if (matchingMethods.size() > 1) {
        // methods by same name but different case.
        for (Iterator<Method> it = matchingMethods.iterator(); it.hasNext(); ) {
            Method m = it.next();
            if (!m.getName().equals(mangledMethodName)) {
                it.remove();
            }
        }
    }
    if (matchingMethods.isEmpty()) {
        throw new RuntimeException("Multiple methods with a case-insensitive match were found for, " + methodName + ", in " + klass + ". Candidates:\n" + candidates);
    }
    if (matchingMethods.size() > 1) {
        throw new RuntimeException("Found more than one matching method. Please specify the types of the parameters. " + "Candidates:\n" + matchingMethods);
    }
    return invoke(klass, obj, matchingMethods.get(0), args);
}
Example 4
Project: gwt.svn-master  File: JsoEval.java View source code
/**
   * A convenience form of 
   * [email protected] #call(Class, Object, String, Class[], Object...)} for use directly
   * by users in a debugger. This method guesses at the types of the method
   * based on the values of [email protected] args}.
   */
public static Object callEx(Class klass, Object obj, String methodName, Object... args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
    if (args == null) {
        // A single-argument varargs null can come in unboxed  
        args = new Object[] { null };
    }
    if (obj != null) {
        if (!obj.getClass().getName().equals(JSO_IMPL_CLASS)) {
            throw new RuntimeException(obj + " is not a JavaScriptObject.");
        }
    }
    // First check java.lang.Object methods for exact matches
    Method[] methods = Object.class.getMethods();
    nextMethod: for (Method m : methods) {
        if (m.getName().equals(methodName)) {
            Class[] types = m.getParameterTypes();
            if (types.length != args.length) {
                continue;
            }
            for (int i = 0, j = 0; i < args.length; ++i, ++j) {
                if (!isAssignable(types[i], args[j])) {
                    continue nextMethod;
                }
            }
            return m.invoke(obj, args);
        }
    }
    ClassLoader ccl = getCompilingClassLoader(klass, obj);
    boolean isJso = isJso(ccl, klass);
    boolean isStaticifiedDispatch = isJso && obj != null;
    int actualNumArgs = isStaticifiedDispatch ? args.length + 1 : args.length;
    ArrayList<Method> matchingMethods = new ArrayList<Method>(Arrays.asList(isJso ? getSisterJsoImpl(klass, ccl).getMethods() : getJsoImplClass(ccl).getMethods()));
    String mangledMethodName = mangleMethod(klass, methodName, isJso, isStaticifiedDispatch);
    // Filter the methods in multiple passes to give better error messages.
    for (Iterator<Method> it = matchingMethods.iterator(); it.hasNext(); ) {
        Method m = it.next();
        if (!m.getName().equalsIgnoreCase(mangledMethodName)) {
            it.remove();
        }
    }
    if (matchingMethods.isEmpty()) {
        throw new RuntimeException("No methods by the name, " + methodName + ", could be found in " + klass);
    }
    ArrayList<Method> candidates = new ArrayList<Method>(matchingMethods);
    for (Iterator<Method> it = matchingMethods.iterator(); it.hasNext(); ) {
        Method m = it.next();
        if (m.getParameterTypes().length != actualNumArgs) {
            it.remove();
        }
    }
    if (matchingMethods.isEmpty()) {
        throw new RuntimeException("No methods by the name, " + methodName + ", in " + klass + " accept " + args.length + " parameters. Candidates are:\n" + candidates);
    }
    candidates = new ArrayList<Method>(matchingMethods);
    nextMethod: for (Iterator<Method> it = matchingMethods.iterator(); it.hasNext(); ) {
        Method m = it.next();
        Class[] methodTypes = m.getParameterTypes();
        for (int i = isStaticifiedDispatch ? 1 : 0, j = 0; i < methodTypes.length; ++i, ++j) {
            if (!isAssignable(methodTypes[i], args[j])) {
                it.remove();
                continue nextMethod;
            }
        }
    }
    if (matchingMethods.isEmpty()) {
        throw new RuntimeException("No methods accepting " + Arrays.asList(args) + " were found for, " + methodName + ", in " + klass + ". Candidates:\n" + candidates);
    }
    candidates = new ArrayList<Method>(matchingMethods);
    if (matchingMethods.size() > 1) {
        // methods by same name but different case.
        for (Iterator<Method> it = matchingMethods.iterator(); it.hasNext(); ) {
            Method m = it.next();
            if (!m.getName().equals(mangledMethodName)) {
                it.remove();
            }
        }
    }
    if (matchingMethods.isEmpty()) {
        throw new RuntimeException("Multiple methods with a case-insensitive match were found for, " + methodName + ", in " + klass + ". Candidates:\n" + candidates);
    }
    if (matchingMethods.size() > 1) {
        throw new RuntimeException("Found more than one matching method. Please specify the types of the parameters. " + "Candidates:\n" + matchingMethods);
    }
    return invoke(klass, obj, matchingMethods.get(0), args);
}
Example 5
Project: scalagwt-gwt-master  File: JsoEval.java View source code
/**
   * A convenience form of 
   * [email protected] #call(Class, Object, String, Class[], Object...)} for use directly
   * by users in a debugger. This method guesses at the types of the method
   * based on the values of [email protected] args}.
   */
public static Object callEx(Class klass, Object obj, String methodName, Object... args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
    if (args == null) {
        // A single-argument varargs null can come in unboxed  
        args = new Object[] { null };
    }
    if (obj != null) {
        if (!obj.getClass().getName().equals(JSO_IMPL_CLASS)) {
            throw new RuntimeException(obj + " is not a JavaScriptObject.");
        }
    }
    // First check java.lang.Object methods for exact matches
    Method[] methods = Object.class.getMethods();
    nextMethod: for (Method m : methods) {
        if (m.getName().equals(methodName)) {
            Class[] types = m.getParameterTypes();
            if (types.length != args.length) {
                continue;
            }
            for (int i = 0, j = 0; i < args.length; ++i, ++j) {
                if (!isAssignable(types[i], args[j])) {
                    continue nextMethod;
                }
            }
            return m.invoke(obj, args);
        }
    }
    ClassLoader ccl = getCompilingClassLoader(klass, obj);
    boolean isJso = isJso(ccl, klass);
    boolean isStaticifiedDispatch = isJso && obj != null;
    int actualNumArgs = isStaticifiedDispatch ? args.length + 1 : args.length;
    ArrayList<Method> matchingMethods = new ArrayList<Method>(Arrays.asList(isJso ? getSisterJsoImpl(klass, ccl).getMethods() : getJsoImplClass(ccl).getMethods()));
    String mangledMethodName = mangleMethod(klass, methodName, isJso, isStaticifiedDispatch);
    // Filter the methods in multiple passes to give better error messages.
    for (Iterator<Method> it = matchingMethods.iterator(); it.hasNext(); ) {
        Method m = it.next();
        if (!m.getName().equalsIgnoreCase(mangledMethodName)) {
            it.remove();
        }
    }
    if (matchingMethods.isEmpty()) {
        throw new RuntimeException("No methods by the name, " + methodName + ", could be found in " + klass);
    }
    ArrayList<Method> candidates = new ArrayList<Method>(matchingMethods);
    for (Iterator<Method> it = matchingMethods.iterator(); it.hasNext(); ) {
        Method m = it.next();
        if (m.getParameterTypes().length != actualNumArgs) {
            it.remove();
        }
    }
    if (matchingMethods.isEmpty()) {
        throw new RuntimeException("No methods by the name, " + methodName + ", in " + klass + " accept " + args.length + " parameters. Candidates are:\n" + candidates);
    }
    candidates = new ArrayList<Method>(matchingMethods);
    nextMethod: for (Iterator<Method> it = matchingMethods.iterator(); it.hasNext(); ) {
        Method m = it.next();
        Class[] methodTypes = m.getParameterTypes();
        for (int i = isStaticifiedDispatch ? 1 : 0, j = 0; i < methodTypes.length; ++i, ++j) {
            if (!isAssignable(methodTypes[i], args[j])) {
                it.remove();
                continue nextMethod;
            }
        }
    }
    if (matchingMethods.isEmpty()) {
        throw new RuntimeException("No methods accepting " + Arrays.asList(args) + " were found for, " + methodName + ", in " + klass + ". Candidates:\n" + candidates);
    }
    candidates = new ArrayList<Method>(matchingMethods);
    if (matchingMethods.size() > 1) {
        // methods by same name but different case.
        for (Iterator<Method> it = matchingMethods.iterator(); it.hasNext(); ) {
            Method m = it.next();
            if (!m.getName().equals(mangledMethodName)) {
                it.remove();
            }
        }
    }
    if (matchingMethods.isEmpty()) {
        throw new RuntimeException("Multiple methods with a case-insensitive match were found for, " + methodName + ", in " + klass + ". Candidates:\n" + candidates);
    }
    if (matchingMethods.size() > 1) {
        throw new RuntimeException("Found more than one matching method. Please specify the types of the parameters. " + "Candidates:\n" + matchingMethods);
    }
    return invoke(klass, obj, matchingMethods.get(0), args);
}
Example 6
Project: gwt-master  File: JsoEval.java View source code
/**
   * A convenience form of
   * [email protected] #call(Class, Object, String, Class[], Object...)} for use directly
   * by users in a debugger. This method guesses at the types of the method
   * based on the values of [email protected] args}.
   */
public static Object callEx(Class klass, Object obj, String methodName, Object... args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
    if (args == null) {
        // A single-argument varargs null can come in unboxed
        args = new Object[] { null };
    }
    if (obj != null) {
        if (!obj.getClass().getName().equals(JSO_IMPL_CLASS)) {
            throw new RuntimeException(obj + " is not a JavaScriptObject.");
        }
    }
    // First check java.lang.Object methods for exact matches
    Method[] methods = Object.class.getMethods();
    nextMethod: for (Method m : methods) {
        if (m.getName().equals(methodName)) {
            Class[] types = m.getParameterTypes();
            if (types.length != args.length) {
                continue;
            }
            for (int i = 0, j = 0; i < args.length; ++i, ++j) {
                if (!isAssignable(types[i], args[j])) {
                    continue nextMethod;
                }
            }
            return m.invoke(obj, args);
        }
    }
    ClassLoader ccl = getCompilingClassLoader(klass, obj);
    boolean isJso = isJso(ccl, klass);
    boolean isStaticifiedDispatch = isJso && obj != null;
    int actualNumArgs = isStaticifiedDispatch ? args.length + 1 : args.length;
    ArrayList<Method> matchingMethods = new ArrayList<Method>(Arrays.asList(isJso ? getSisterJsoImpl(klass, ccl).getMethods() : getJsoImplClass(ccl).getMethods()));
    String mangledMethodName = mangleMethod(klass, methodName, isJso, isStaticifiedDispatch);
    // Filter the methods in multiple passes to give better error messages.
    for (Iterator<Method> it = matchingMethods.iterator(); it.hasNext(); ) {
        Method m = it.next();
        if (!m.getName().equalsIgnoreCase(mangledMethodName)) {
            it.remove();
        }
    }
    if (matchingMethods.isEmpty()) {
        throw new RuntimeException("No methods by the name, " + methodName + ", could be found in " + klass);
    }
    ArrayList<Method> candidates = new ArrayList<Method>(matchingMethods);
    for (Iterator<Method> it = matchingMethods.iterator(); it.hasNext(); ) {
        Method m = it.next();
        if (m.getParameterTypes().length != actualNumArgs) {
            it.remove();
        }
    }
    if (matchingMethods.isEmpty()) {
        throw new RuntimeException("No methods by the name, " + methodName + ", in " + klass + " accept " + args.length + " parameters. Candidates are:\n" + candidates);
    }
    candidates = new ArrayList<Method>(matchingMethods);
    nextMethod: for (Iterator<Method> it = matchingMethods.iterator(); it.hasNext(); ) {
        Method m = it.next();
        Class[] methodTypes = m.getParameterTypes();
        for (int i = isStaticifiedDispatch ? 1 : 0, j = 0; i < methodTypes.length; ++i, ++j) {
            if (!isAssignable(methodTypes[i], args[j])) {
                it.remove();
                continue nextMethod;
            }
        }
    }
    if (matchingMethods.isEmpty()) {
        throw new RuntimeException("No methods accepting " + Arrays.asList(args) + " were found for, " + methodName + ", in " + klass + ". Candidates:\n" + candidates);
    }
    candidates = new ArrayList<Method>(matchingMethods);
    if (matchingMethods.size() > 1) {
        // methods by same name but different case.
        for (Iterator<Method> it = matchingMethods.iterator(); it.hasNext(); ) {
            Method m = it.next();
            if (!m.getName().equals(mangledMethodName)) {
                it.remove();
            }
        }
    }
    if (matchingMethods.isEmpty()) {
        throw new RuntimeException("Multiple methods with a case-insensitive match were found for, " + methodName + ", in " + klass + ". Candidates:\n" + candidates);
    }
    if (matchingMethods.size() > 1) {
        throw new RuntimeException("Found more than one matching method. Please specify the types of the parameters. " + "Candidates:\n" + matchingMethods);
    }
    return invoke(klass, obj, matchingMethods.get(0), args);
}
Example 7
Project: gwt-test-utils-master  File: JsArrayMixedTest.java View source code
@Before
public void beforeJsArrayIntegerTest() {
    // Given
    jsArrayMixed = JavaScriptObject.createArray().cast();
    assertThat(jsArrayMixed.length()).isEqualTo(0);
    // When
    jsArrayMixed.set(4, true);
    // Then
    assertThat(jsArrayMixed.length()).isEqualTo(5);
    assertThat(jsArrayMixed.getBoolean(3)).isFalse();
    assertThat(jsArrayMixed.getString(3)).isNull();
    assertThat(jsArrayMixed.getBoolean(4)).isTrue();
    assertThat(jsArrayMixed.getString(4)).isEqualTo("true");
}
Example 8
Project: kevoree-library-master  File: latexEditorRPC.java View source code
public static void callForCompile(final latexEditorFileExplorer explorer) {
    final JavaScriptObject window = newWindow("", null, null);
    latexEditorService.App.getInstance().saveFile(explorer.getSelectedFilePath(), AceEditorWrapper.getText(), new AsyncCallback<Boolean>() {

        @Override
        public void onFailure(Throwable caught) {
            Window.alert("Error while saving file");
        }

        @Override
        public void onSuccess(Boolean result) {
            final String selectedPath = explorer.getSelectedCompileRootFilePath();
            if (selectedPath.equals("") || selectedPath.equals(null)) {
                Window.alert("Please select root file");
                return;
            }
            try {
                latexEditorService.App.getInstance().compile(selectedPath, new AsyncCallback<String>() {

                    @Override
                    public void onFailure(Throwable caught) {
                        Window.alert("Error while connecting to server");
                    }

                    @Override
                    public void onSuccess(final String compileUUID) {
                        final boolean[] compileresult = { false };
                        final int[] nbtry = { 0 };
                        Scheduler.get().scheduleFixedPeriod(new Scheduler.RepeatingCommand() {

                            @Override
                            public boolean execute() {
                                if (nbtry[0] > 10) {
                                    return false;
                                }
                                if (compileresult[0]) {
                                    return false;
                                }
                                latexEditorService.App.getInstance().compileresult(compileUUID, new AsyncCallback<String[]>() {

                                    @Override
                                    public void onFailure(Throwable caught) {
                                        nbtry[0] = nbtry[0] + 1;
                                    }

                                    @Override
                                    public void onSuccess(String[] result) {
                                        if (result.length != 2) {
                                            nbtry[0] = nbtry[0] + 1;
                                        } else {
                                            if (result[0].trim().equals("true")) {
                                                String pdfpath = GWT.getModuleBaseURL() + "rawfile?file=" + selectedPath.replace(".tex", ".pdf");
                                                setWindowTarget(window, pdfpath);
                                                compileresult[0] = true;
                                            } else {
                                                String pdfpath = GWT.getModuleBaseURL() + "rawfile?file=" + selectedPath.replace(".tex", ".log");
                                                setWindowTarget(window, pdfpath);
                                                compileresult[0] = true;
                                            }
                                        }
                                    }
                                });
                                return true;
                            }
                        }, 1500);
                    }
                });
            } catch (Exception e) {
                Window.alert(e.getMessage());
            }
        }
    });
}
Example 9
Project: ovirt-engine-master  File: EntityObject.java View source code
protected static <T> EntityObject create(T businessEntity) {
    EntityObject obj = JavaScriptObject.createObject().cast();
    //$NON-NLS-1$
    String entityId = "";
    if (businessEntity instanceof BusinessEntity) {
        entityId = ((BusinessEntity<?>) businessEntity).getId().toString();
    } else if (businessEntity instanceof IVdcQueryable) {
        entityId = ((IVdcQueryable) businessEntity).getQueryableId().toString();
    }
    //$NON-NLS-1$
    obj.setValueAsString("id", entityId);
    return obj;
}
Example 10
Project: gwtupload-master  File: MultipleFileUpload.java View source code
public List<String> getFilenames() {
    ArrayList<String> result = new ArrayList<String>();
    JavaScriptObject rawFileList = getElement().getPropertyJSO("files");
    if (rawFileList == null) {
        // IE does not support multiple-select
        result.add(InputElement.as(getElement()).getValue());
    } else {
        FileList fileList = rawFileList.cast();
        for (int i = 0; i < fileList.getLength(); ++i) {
            result.add(fileList.item(i).getName());
        }
    }
    return result;
}
Example 11
Project: swellrt-master  File: TemplateNodeMutationHandler.java View source code
/**
   * Creates a renderer for <template> doodads.
   */
static TemplateNodeMutationHandler create() {
    final PartIdFactory partIdFactory = SessionPartIdFactory.get();
    CajolerFacade cajoler = CajolerFacade.instance();
    final JavaScriptObject taming = cajoler.getTaming();
    PluginContextFactory defaultFactory = new PluginContextFactory() {

        @Override
        public PluginContext create(ContentElement doodad) {
            return new PluginContext(doodad, partIdFactory, taming);
        }
    };
    return new TemplateNodeMutationHandler(cajoler, defaultFactory);
}
Example 12
Project: ahome-sencha-shared-master  File: DomConfig.java View source code
public JavaScriptObject getJsObject() {
    JavaScriptObject jsObj = JsoHelper.createObject();
    if (tag != null)
        JsoHelper.setAttribute(jsObj, "tag", tag);
    if (id != null)
        JsoHelper.setAttribute(jsObj, "id", id);
    if (cls != null)
        JsoHelper.setAttribute(jsObj, "cls", cls);
    if (style != null)
        JsoHelper.setAttribute(jsObj, "style", style);
    if (html != null)
        JsoHelper.setAttribute(jsObj, "html", html);
    for (@SuppressWarnings("rawtypes") Iterator iterator = otherConfig.keySet().iterator(); iterator.hasNext(); ) {
        String attribute = (String) iterator.next();
        String value = (String) otherConfig.get(attribute);
        JsoHelper.setAttribute(jsObj, attribute, value);
    }
    if (children != null) {
        JavaScriptObject[] childrenJS = new JavaScriptObject[children.size()];
        int i = 0;
        for (@SuppressWarnings("rawtypes") Iterator it = children.iterator(); it.hasNext(); i++) {
            DomConfig config = (DomConfig) it.next();
            childrenJS[i] = config.getJsObject();
        }
        JsoHelper.setAttribute(jsObj, "children", childrenJS);
    }
    return jsObj;
}
Example 13
Project: ahome-touch-master  File: ComponentFactory.java View source code
/**
     * Return a Component from the passed native component object.
     * 
     * @param jsObj
     *            native object
     * @return the corresponding Component.
     * @see com.ait.toolkit.sencha.touch.client.core.Component
     */
public static Component getComponent(JavaScriptObject jsObj) {
    Object componentJ = JsoHelper.getAttributeAsObject(jsObj, "__compJ");
    if (componentJ != null) {
        return (Component) componentJ;
    }
    String xtype = getXType(jsObj);
    if (xtype == null) {
        return null;
    }
    if (xtype.equalsIgnoreCase(XType.ACTONSHEET.getValue())) {
        return new ActionSheet(jsObj);
    } else if (xtype.equalsIgnoreCase(XType.AUDIO.getValue())) {
        return new Audio(jsObj);
    } else if (xtype.equalsIgnoreCase(XType.BUTTON.getValue())) {
        return new Button(jsObj);
    } else if (xtype.equalsIgnoreCase(XType.CAROUSEL.getValue())) {
        return new Carousel(jsObj);
    } else if (xtype.equalsIgnoreCase(XType.CHECKBOX_FIELD.getValue())) {
        return new CheckBox(jsObj);
    } else if (xtype.equalsIgnoreCase(XType.CHART.getValue())) {
        return new CartesianChart(jsObj);
    } else if (xtype.equalsIgnoreCase(XType.CONTAINER.getValue())) {
        return new Container(jsObj);
    }
    return null;
}
Example 14
Project: aokp-gerrit-master  File: NewChangeScreenBar.java View source code
private void save(ChangeScreen sel) {
    removeFromParent();
    Dispatcher.changeScreen2 = sel == ChangeScreen.CHANGE_SCREEN2;
    if (Gerrit.isSignedIn()) {
        Gerrit.getUserAccount().getGeneralPreferences().setChangeScreen(sel);
        Prefs in = Prefs.createObject().cast();
        in.change_screen(sel.name());
        AccountApi.self().view("preferences").background().post(in, new AsyncCallback<JavaScriptObject>() {

            @Override
            public void onFailure(Throwable caught) {
            }

            @Override
            public void onSuccess(JavaScriptObject result) {
            }
        });
    } else {
        Cookies.setCookie(Dispatcher.COOKIE_CS2, Dispatcher.changeScreen2 ? "1" : "0", new Date(System.currentTimeMillis() + 7 * 24 * 3600 * 1000));
    }
}
Example 15
Project: ArcBees-Common-master  File: Status.java View source code
public static Status valueOf(JavaScriptObject jsObject) {
    JSONObject json = new JSONObject(jsObject);
    JSONString returnedStatus = json.get(JSON_STATUS).isString();
    for (Status status : Status.values()) {
        if (status.toString().equals(returnedStatus.stringValue())) {
            return status;
        }
    }
    return Status.Unknown;
}
Example 16
Project: Bam-master  File: DataSelectionEvent.java View source code
public static void fire(HasDataSelectionEventHandlers source, Object sender, JavaScriptObject data) {
    DataSelectionEvent event = new DataSelectionEvent(sender);
    JSONObject array = new JSONObject(data);
    event.series = new LinkedList<Series>();
    for (String key : array.keySet()) {
        JSONObject obj = array.get(key).isObject();
        if (obj != null) {
            Series series1 = JavaScriptObject.createObject().cast();
            series1.setValue(obj.get("value").isNumber().doubleValue());
            series1.setColor(obj.get("fillColor").isString().stringValue());
            event.series.add(series1);
        }
    }
    source.fireEvent(event);
}
Example 17
Project: che-master  File: GwtReflectionUtils.java View source code
public static <T> T callPrivateMethod(Object target, String methodName, Object... args) {
    if (target instanceof JavaScriptObject) {
        throw new UnsupportedOperationException("Cannot call instance method on Overlay types without specifying its base type");
    }
    Method method = findMethod(target.getClass(), methodName, args);
    if (method == null) {
        throw new RuntimeException("Cannot find method '" + target.getClass().getName() + "." + methodName + "(..)'");
    }
    return (T) callPrivateMethod(target, method, args);
}
Example 18
Project: che-plugins-master  File: OrionLinkedModelOverlay.java View source code
@Override
public final void setGroups(List<LinkedModelGroup> groups) {
    JsArray<OrionLinkedModelGroupOverlay> arr = JavaScriptObject.createArray().cast();
    for (LinkedModelGroup group : groups) {
        if (group instanceof OrionLinkedModelGroupOverlay) {
            arr.push((OrionLinkedModelGroupOverlay) group);
        } else {
            throw new IllegalArgumentException("This implementation supports only OrionLinkedModelGroupOverlay groups");
        }
    }
    setGroups(arr);
}
Example 19
Project: crux-master  File: JsonEncoderProxyCreator.java View source code
@Override
protected void generateProxyMethods(SourcePrinter srcWriter) {
    srcWriter.println("public JavaScriptObject toJavaScriptObject(" + targetObjectType.getParameterizedQualifiedSourceName() + " object){");
    srcWriter.println("JSONValue result = " + serializerVariable + ".encode(object);");
    srcWriter.println("if (result == null || result.isNull() != null || result.isObject() == null){");
    srcWriter.println("return null;");
    srcWriter.println("}");
    srcWriter.println("return JsUtils.fromJSONValue(result);");
    srcWriter.println("}");
    srcWriter.println();
    srcWriter.println("public String encode(" + targetObjectType.getParameterizedQualifiedSourceName() + " object){");
    srcWriter.println("JSONValue result = " + serializerVariable + ".encode(object);");
    srcWriter.println("if (result == null || result.isNull() != null){");
    srcWriter.println("return null;");
    srcWriter.println("}");
    if (targetObjectType.isAssignableTo(stringType) || targetObjectType.isEnum() != null || targetObjectType.getQualifiedSourceName().equals(BigInteger.class.getCanonicalName()) || targetObjectType.getQualifiedSourceName().equals(BigDecimal.class.getCanonicalName())) {
        srcWriter.println("if (result.isString() != null){");
        srcWriter.println("return result.isString().stringValue();");
        srcWriter.println("}");
    }
    srcWriter.println("return result.toString();");
    srcWriter.println("}");
    srcWriter.println();
    srcWriter.println("public " + targetObjectType.getParameterizedQualifiedSourceName() + " fromJavaScriptObject(JavaScriptObject object){");
    srcWriter.println("JSONValue jsonValue= JsUtils.toJSONValue(object);");
    srcWriter.println("return " + serializerVariable + ".decode(jsonValue);");
    srcWriter.println("}");
    srcWriter.println();
    srcWriter.println("public " + targetObjectType.getParameterizedQualifiedSourceName() + " decode(String jsonText){");
    JClassType objectClassType = targetObjectType.isClassOrInterface();
    if (objectClassType != null && objectClassType.isAssignableTo(javascriptObjectType)) {
        srcWriter.println(targetObjectType.getParameterizedQualifiedSourceName() + " result = " + JsonUtils.class.getCanonicalName() + ".safeEval(jsonText);");
        srcWriter.println("return result;");
    }
    srcWriter.println("JSONValue jsonValue = JSONParser.parseStrict(jsonText);");
    srcWriter.println("return " + serializerVariable + ".decode(jsonValue);");
    srcWriter.println("}");
    srcWriter.println();
}
Example 20
Project: dashbuilder-master  File: DataSelectionEvent.java View source code
public static void fire(HasDataSelectionEventHandlers source, Object sender, JavaScriptObject data) {
    DataSelectionEvent event = new DataSelectionEvent(sender);
    JSONObject array = new JSONObject(data);
    event.series = new LinkedList<Series>();
    for (String key : array.keySet()) {
        JSONObject obj = array.get(key).isObject();
        if (obj != null) {
            Series series1 = JavaScriptObject.createObject().cast();
            series1.setValue(obj.get("value").isNumber().doubleValue());
            series1.setColor(obj.get("fillColor").isString().stringValue());
            event.series.add(series1);
        }
    }
    source.fireEvent(event);
}
Example 21
Project: DevTools-master  File: GwtReflectionUtils.java View source code
public static <T> T callPrivateMethod(Object target, String methodName, Object... args) {
    if (target instanceof JavaScriptObject) {
        throw new UnsupportedOperationException("Cannot call instance method on Overlay types without specifying its base type");
    }
    Method method = findMethod(target.getClass(), methodName, args);
    if (method == null) {
        throw new RuntimeException("Cannot find method '" + target.getClass().getName() + "." + methodName + "(..)'");
    }
    return (T) callPrivateMethod(target, method, args);
}
Example 22
Project: framework-master  File: JavaScriptManagerConnector.java View source code
public void sendRpc(String name, JsArray<JavaScriptObject> arguments) {
    Object[] parameters = new Object[] { name, Util.jso2json(arguments) };
    /*
         * Must invoke manually as the RPC interface can't be used in GWT
         * because of the JSONArray parameter
         */
    ServerRpcQueue rpcQueue = ServerRpcQueue.get(getConnection());
    rpcQueue.add(new JavaScriptMethodInvocation(getConnectorId(), "com.vaadin.ui.JavaScript$JavaScriptCallbackRpc", "call", parameters), false);
    rpcQueue.flush();
}
Example 23
Project: gerrit-master  File: DownloadUrlLink.java View source code
@Override
public void onClick(ClickEvent event) {
    event.preventDefault();
    event.stopPropagation();
    select();
    GeneralPreferences prefs = Gerrit.getUserPreferences();
    if (Gerrit.isSignedIn() && !schemeName.equals(prefs.downloadScheme())) {
        prefs.downloadScheme(schemeName);
        GeneralPreferences in = GeneralPreferences.create();
        in.downloadScheme(schemeName);
        AccountApi.self().view("preferences").put(in, new AsyncCallback<JavaScriptObject>() {

            @Override
            public void onSuccess(JavaScriptObject result) {
            }

            @Override
            public void onFailure(Throwable caught) {
            }
        });
    }
}
Example 24
Project: gwt-three.js-test-master  File: Mbl3dLoader.java View source code
//fix r74 blender exporter blend keys
//TODO make method
public JsArrayNumber convertMorphVertices(JSONArray morphTargetsVertices) {
    JsArrayNumber arrays = JavaScriptObject.createArray().cast();
    Vector3 axis = THREE.Vector3(1, 0, 0);
    double angle = THREEMath.degToRad(-90);
    boolean needApplyAxisAngle = false;
    LOOP: for (int i = 0; i < morphTargetsVertices.size(); i++) {
        JSONValue avalue = morphTargetsVertices.get(i);
        JSONArray verticesArray = avalue.isArray();
        if (//no need fix
        verticesArray == null) {
            if (!forceApplyAxisAngle) {
                return null;
            } else {
                needApplyAxisAngle = true;
                break LOOP;
            }
        }
        JsArrayNumber verticesNumber = verticesArray.getJavaScriptObject().cast();
        Vector3 vec = THREE.Vector3().fromArray(verticesNumber);
        if (applyAxisAngle) {
            vec.applyAxisAngle(axis, angle);
        }
        //should i make options?
        arrays.push(fixNumber(vec.getX()));
        arrays.push(fixNumber(vec.getY()));
        arrays.push(fixNumber(vec.getZ()));
    }
    if (needApplyAxisAngle) {
        for (int i = 0; i < morphTargetsVertices.size(); i += 3) {
            double x = morphTargetsVertices.get(i).isNumber().doubleValue();
            double y = morphTargetsVertices.get(i + 1).isNumber().doubleValue();
            double z = morphTargetsVertices.get(i + 2).isNumber().doubleValue();
            Vector3 vec = THREE.Vector3(x, y, z);
            vec.applyAxisAngle(axis, angle);
            arrays.push(fixNumber(vec.getX()));
            arrays.push(fixNumber(vec.getY()));
            arrays.push(fixNumber(vec.getZ()));
        }
        LogUtils.log("force apply axis");
    }
    return arrays;
}
Example 25
Project: GWTChromeCast-master  File: JavaScriptObjectHelper.java View source code
public static int[] getAttributeAsIntArray(JavaScriptObject elem, String attr) {
    int[] rtn = null;
    JavaScriptObject hold = getAttributeAsJavaScriptObject(elem, attr);
    if (hold != null) {
        rtn = new int[getJavaScriptObjectArraySize(hold)];
        for (int i = 0; i < rtn.length; i++) {
            rtn[i] = getIntValueFromJavaScriptObjectArray(hold, i);
        }
    }
    return rtn;
}
Example 26
Project: hexa.tools-master  File: DataProxyFastFactoryGenerator.java View source code
public static void generate(JType type, SourceWriter sw, TreeLogger logger) {
    sw.println("public <T> T getData( JavaScriptObject obj )");
    sw.println("{");
    sw.indent();
    // sw.println( "GWT.log( \"A Casting obj : \" + obj.toString() );" );
    // sw.println( "GWT.log( \"Jsoncontent:\"+HexaTools.toJSON(obj) );" );
    // sw.println( type.getSimpleSourceName() +
    // "ImplStd impl = "+type.getSimpleSourceName() + "ImplStd.as( obj );"
    // );
    sw.println("return (T)obj;");
    sw.outdent();
    sw.println("}");
}
Example 27
Project: mgwt-master  File: JsLightArrayGwtTest.java View source code
public void testExistingArray() {
    JsArrayString nativeArray = JavaScriptObject.createArray(5).cast();
    nativeArray.set(0, "0");
    nativeArray.set(1, "1");
    nativeArray.set(2, "2");
    nativeArray.set(3, "3");
    nativeArray.set(4, "4");
    JsLightArray<String> array = new JsLightArray<String>(nativeArray);
    assertEquals(5, array.length());
    assertEquals("0", array.get(0));
    assertEquals("1", array.get(1));
    assertEquals("2", array.get(2));
    assertEquals("3", array.get(3));
    assertEquals("4", array.get(4));
    nativeArray.shift();
    nativeArray.shift();
    nativeArray.shift();
    nativeArray.shift();
    nativeArray.shift();
    assertEquals(0, array.length());
}
Example 28
Project: pentaho-commons-gwt-modules-master  File: FileChooserEntryPoint.java View source code
public void openFileChooserDialog(final JavaScriptObject callback, String selectedPath) {
    FileChooserDialog dialog = new FileChooserDialog(FileChooserMode.OPEN, selectedPath, false, true);
    dialog.addFileChooserListener(new FileChooserListener() {

        public void fileSelected(RepositoryFile file, String filePath, String fileName, String title) {
            notifyCallback(callback, file, filePath, fileName, title);
        }

        public void fileSelectionChanged(RepositoryFile file, String filePath, String fileName, String title) {
        }

        public void dialogCanceled() {
            notifyCallbackCanceled(callback);
        }
    });
}
Example 29
Project: pentaho-gwt-modules-master  File: FileChooserEntryPoint.java View source code
public void openFileChooserDialog(final JavaScriptObject callback, String selectedPath) {
    FileChooserDialog dialog = new FileChooserDialog(FileChooserMode.OPEN, selectedPath, false, true);
    dialog.addFileChooserListener(new FileChooserListener() {

        public void fileSelected(RepositoryFile file, String filePath, String fileName, String title) {
            notifyCallback(callback, file, filePath, fileName, title);
        }

        public void fileSelectionChanged(RepositoryFile file, String filePath, String fileName, String title) {
        }

        public void dialogCanceled() {
            notifyCallbackCanceled(callback);
        }
    });
}
Example 30
Project: RedQueryBuilder-master  File: JsConfiguration.java View source code
public final void fireOnTableChange(ObjectArray<TableFilter> filters) {
    JsArray<JsTableFilter> result = (JsArray<JsTableFilter>) JavaScriptObject.createArray();
    for (int i = 0; i < filters.size(); i++) {
        TableFilter tf = filters.get(i);
        JsTableFilter jtf = JsTableFilter.create(tf.getAlias(), tf.getTable().getName());
        result.push(jtf);
    }
    fireOnTableChange2(result);
}
Example 31
Project: rstudio-master  File: SourceSatelliteWindow.java View source code
@Override
protected void onInitialize(LayoutPanel mainPanel, JavaScriptObject params) {
    // read the params and set up window ordinal / title
    SourceWindowParams windowParams = params.cast();
    String title = null;
    if (windowParams != null) {
        pWindowManager_.get().setSourceWindowOrdinal(windowParams.getOrdinal());
        title = windowParams.getTitle();
    }
    if (title == null)
        title = "";
    else
        title += " - ";
    title += "RStudio Source Editor";
    Window.setTitle(title);
    // set up the source window
    SourceWindow sourceWindow = pSourceWindow_.get();
    if (windowParams != null && windowParams.getDocId() != null && windowParams.getSourcePosition() != null) {
        // if this source window is being opened to pop out a particular doc,
        // read that doc's ID and current position so we can restore it 
        sourceWindow.setInitialDoc(windowParams.getDocId(), windowParams.getSourcePosition());
    }
    SourceSatellitePresenter appPresenter = pPresenter_.get();
    // initialize build commands (we want these to work from source windows)
    BuildCommands.setBuildCommandState(RStudioGinjector.INSTANCE.getCommands(), RStudioGinjector.INSTANCE.getSession().getSessionInfo());
    // menu entries aren't accessible from the source window)
    if (Desktop.isDesktop() && Desktop.getFrame().isCocoa()) {
        pFileMRUList_.get();
        pProjectMRUList_.get();
    }
    // initialize working directory
    if (!StringUtil.isNullOrEmpty(windowParams.getWorkingDir())) {
        pEventBus_.get().fireEvent(new WorkingDirChangedEvent(windowParams.getWorkingDir()));
    }
    // make it fill the containing layout panel
    Widget presWidget = appPresenter.asWidget();
    mainPanel.add(presWidget);
    mainPanel.setWidgetLeftRight(presWidget, 0, Unit.PX, 0, Unit.PX);
    mainPanel.setWidgetTopBottom(presWidget, 0, Unit.PX, 0, Unit.PX);
}
Example 32
Project: smartgwt-master  File: BeanValueType.java View source code
private void initializeBeanValueType() {
    requiresGeneration = false;
    final JPrimitiveType primitiveType = valueType.isPrimitive();
    if (primitiveType != null) {
        if (primitiveType == JPrimitiveType.BOOLEAN) {
            beanValueType = findType(PBooleanValueType.class);
            genericType = findType(Boolean.class);
        } else if (primitiveType == JPrimitiveType.FLOAT) {
            beanValueType = findType(PFloatValueType.class);
            genericType = findType(Float.class);
        } else if (primitiveType == JPrimitiveType.DOUBLE) {
            beanValueType = findType(PDoubleValueType.class);
            genericType = findType(Double.class);
        } else if (primitiveType == JPrimitiveType.INT) {
            beanValueType = findType(PIntegerValueType.class);
            genericType = findType(Integer.class);
        } else if (primitiveType == JPrimitiveType.LONG) {
            beanValueType = findType(PLongValueType.class);
            genericType = findType(Long.class);
        }
        return;
    }
    final JEnumType enumType = valueType.isEnum();
    if (enumType != null) {
        genericType = enumType;
        final JType valueEnumType = findType(ValueEnum.class);
        if (Arrays.asList(enumType.getImplementedInterfaces()).contains(valueEnumType)) {
            beanValueType = findType(ValueEnumValueType.class);
        } else {
            beanValueType = findType(EnumValueType.class);
        }
        return;
    }
    final JArrayType arrayType = valueType.isArray();
    if (arrayType != null) {
        genericType = arrayType;
        componentType = arrayType.getComponentType();
        assert componentType != null;
        componentValueType = new BeanValueType(componentType, oracle);
        assert componentValueType != null;
        if (componentType.isPrimitive() != null) {
            if (componentType == JPrimitiveType.BOOLEAN) {
                beanValueType = findType(PBooleanArrayValueType.class);
            } else if (componentType == JPrimitiveType.DOUBLE) {
                beanValueType = findType(PDoubleArrayValueType.class);
            } else if (componentType == JPrimitiveType.FLOAT) {
                beanValueType = findType(PFloatArrayValueType.class);
            } else if (componentType == JPrimitiveType.INT) {
                beanValueType = findType(PIntegerArrayValueType.class);
            } else if (componentType == JPrimitiveType.LONG) {
                beanValueType = findType(PLongArrayValueType.class);
            }
        } else if (componentType.isInterface() != null) {
            beanValueType = findType(InterfaceArrayValueType.class);
            // We have to generate for isAssignableFrom to work
            requiresGeneration = true;
            // The generic type for the subclass is the component type,
            // rather than the array type
            genericType = componentType.isInterface();
        } else if (componentType instanceof JClassType) {
            beanValueType = findType(ObjectArrayValueType.class);
            constructorTakesEmptyArray = true;
            genericType = (JClassType) componentType;
        } else {
            throw new IllegalStateException("componentType " + componentType.getQualifiedSourceName() + " is not a primitive, an interface, or a class");
        }
        return;
    }
    final JClassType classType = valueType.isClass();
    if (classType != null) {
        genericType = classType;
        if (classType == findType(Integer.class)) {
            beanValueType = findType(IntegerValueType.class);
        } else if (classType == findType(Boolean.class)) {
            beanValueType = findType(BooleanValueType.class);
        } else if (classType == findType(Float.class)) {
            beanValueType = findType(FloatValueType.class);
        } else if (classType == findType(Double.class)) {
            beanValueType = findType(DoubleValueType.class);
        } else if (classType == findType(Long.class)) {
            beanValueType = findType(LongValueType.class);
        } else if (classType == findType(Number.class)) {
            beanValueType = findType(NumberValueType.class);
        } else if (classType == findType(String.class)) {
            beanValueType = findType(StringValueType.class);
        } else if (classType == findType(Date.class)) {
            beanValueType = findType(DateValueType.class);
        } else if (classType.isAssignableTo(findType(JavaScriptObject.class))) {
            beanValueType = findType(JsoValueType.class);
        } else if (classType.isAssignableTo(findType(DataSource.class))) {
            beanValueType = findType(DataSourceBaseValueType.class);
            // Need to generate, in order to get newInstance(JavaScriptObject object)
            requiresGeneration = true;
            hasSetJavaScriptObject = true;
        } else if (classType.isAssignableTo(findType(Canvas.class))) {
            beanValueType = findType(CanvasBaseValueType.class);
            // Need to generate, in order to get newInstance(JavaScriptObject object)
            requiresGeneration = true;
            hasSetJavaScriptObject = true;
        } else if (jsObjConstructor != null) {
            beanValueType = findType(JsoWrapperValueType.class);
            // Need to generate, in order to get newInstance(JavaScriptObject object)
            requiresGeneration = true;
        } else {
            beanValueType = findType(OtherValueType.class);
        }
        return;
    }
    final JClassType interfaceType = valueType.isInterface();
    if (interfaceType != null) {
        genericType = interfaceType;
        beanValueType = findType(InterfaceValueType.class);
        // Need to generate, because otherwise we can't use instanceof
        requiresGeneration = true;
        return;
    }
    System.out.println("No specific BeanValueType subclass for " + getQualifiedTypeName());
}
Example 33
Project: solmix-master  File: EventSerializer.java View source code
/**
     * [email protected]}
     * 
     * @see org.solmix.atmosphere.client.ClientSerializer#serialize(java.lang.Object)
     */
@Override
public String serialize(Object message) throws SerializationException {
    if (message instanceof JsObject) {
        return JSON.encode(((JsObject) message).getJsObj());
    }
    if (message instanceof JavaScriptObject) {
        return JSON.encode((JavaScriptObject) message);
    } else {
        throw new SerializationException("The serialized object must be JavaScriptObject ,but this object is:" + message.getClass().getName());
    }
}
Example 34
Project: timesheets-master  File: CommandLineSuggesterConnector.java View source code
@Override
public Command handleKeyboard(JavaScriptObject data, int hashId, String keyString, int keyCode, GwtAceKeyboardEvent e) {
    if (suggesting) {
        return keyPressWhileSuggesting(keyCode);
    }
    if (e == null) {
        return Command.DEFAULT;
    }
    if (keyCode == 13) {
        //Enter
        commandLineRpc.apply();
        //ignore enter
        return Command.NULL;
    } else if ((keyCode == 32 && e.isCtrlKey())) {
        //Ctrl+Space
        startSuggesting();
        return Command.NULL;
    } else if (//@
    (keyCode == 50 && e.isShiftKey()) || //#
    (keyCode == 51 && e.isShiftKey()) || //$
    (keyCode == 52 && e.isShiftKey()) || (keyCode == 56 && e.isShiftKey())) {
        //*
        startSuggestingOnNextSelectionChange = true;
        widget.addSelectionChangeListener(this);
        return Command.DEFAULT;
    //            startSuggesting();
    //            return Command.DEFAULT;
    }
    return Command.DEFAULT;
}
Example 35
Project: totoe-master  File: XmlParserImpl.java View source code
// ---------------------------------------------------------- parse methods
public Document parse(String xml, String namespaces) {
    if (xml == null || xml.trim().length() == 0) {
        return null;
    }
    try {
        JavaScriptObject documentJso = parseImpl(xml, namespaces);
        return NodeFactory.create(documentJso);
    } catch (JavaScriptException e) {
        throw new XmlParseException(e.getMessage(), e);
    }
}
Example 36
Project: turbogwt-master  File: JsArrays.java View source code
public static <T extends JavaScriptObject> T[] toArray(JsArray<? extends T> values) {
    if (GWT.isScript()) {
        return reinterpretCast(values);
    } else {
        int length = values.length();
        @SuppressWarnings("unchecked") T[] ret = (T[]) new JavaScriptObject[length];
        for (int i = 0, l = length; i < l; i++) {
            ret[i] = values.get(i);
        }
        return ret;
    }
}
Example 37
Project: vaadin-master  File: JavaScriptManagerConnector.java View source code
public void sendRpc(String name, JsArray<JavaScriptObject> arguments) {
    Object[] parameters = new Object[] { name, Util.jso2json(arguments) };
    /*
         * Must invoke manually as the RPC interface can't be used in GWT
         * because of the JSONArray parameter
         */
    ServerRpcQueue rpcQueue = ServerRpcQueue.get(getConnection());
    rpcQueue.add(new JavaScriptMethodInvocation(getConnectorId(), "com.vaadin.ui.JavaScript$JavaScriptCallbackRpc", "call", parameters), false);
    rpcQueue.flush();
}
Example 38
Project: ahome-ext-master  File: DragData.java View source code
public List<BaseModel> getRecords() {
    List<BaseModel> toReturn = new ArrayList<BaseModel>();
    JavaScriptObject[] records = JsoHelper.getAttributeAsJavaScriptObjectArray(jsObj, "records");
    for (int i = 0; i < records.length; i++) {
        toReturn.add(BaseModel.from(JsoHelper.getAttributeAsJavaScriptObject(records[i], "data")));
    }
    return toReturn;
}
Example 39
Project: forplay-master  File: ExternalInterface.java View source code
/**
     * Invoke a function in the container.
     * At most three parameters are supported.
     *
     * @param methodName name of the method to invoke
     * @param params zero or more arrays each containing a method parameter
     *  as the first element in the array
     * @return an array containing the returned value as its first element
     */
public static JavaScriptObject call(String methodName, JavaScriptObject... params) {
    if (!ExternalInterface.isAvailable())
        return null;
    JavaScriptObject param0 = params.length > 0 ? params[0] : null;
    JavaScriptObject param1 = params.length > 1 ? params[1] : null;
    JavaScriptObject param2 = params.length > 2 ? params[2] : null;
    return call(methodName, param0, param1, param2);
}
Example 40
Project: FURCAS-master  File: ColorPalette.java View source code
@Override
protected void onRender(Element target, int index) {
    setElement(DOM.createDiv(), target, index);
    super.onRender(target, index);
    if (template == null) {
        String html = "<tpl for=\".\"><a href=\"#\" class=\"color-{.}\"><em><span style=\"background:#{.}\" unselectable=\"on\"> </span></em></a></tpl>";
        setTemplate(XTemplate.create(html));
    }
    JavaScriptObject toJavaScriptArray = JsUtil.toJavaScriptArray(getColors());
    getTemplate().overwrite(el().dom, toJavaScriptArray);
    sinkEvents(Event.ONCLICK | Event.ONMOUSEOVER | Event.ONMOUSEOUT);
}
Example 41
Project: GKEngine-master  File: ComHandler.java View source code
private void doProcess(List sources, List targets, BaseEvent be) {
    Object value = null;
    if (!sources.isEmpty()) {
        Object obj = sources.get(0);
        EventValue ev;
        if (obj instanceof EventValue) {
            ev = (EventValue) obj;
        } else {
            ev = EventFactory.convertToEventValue(sources.get(0));
        }
        String content = ev.getContent();
        if (ev.getType() == Type.EXPR) {
            value = eval(content);
        } else if (ev.getType() == Type.ID) {
            value = getAttributeValue(content);
            if (content.startsWith("!")) {
                value = reverseValue(getAttributeValue(content.replaceFirst("!", "")));
            } else if (content.startsWith(IEventConstants.TYPE_DATA)) {
                value = content.substring(1);
            }
        } else if (ev.getType() == Type.STRING) {
            value = content;
        }
    }
    if (value != null && !targets.isEmpty()) {
        for (Iterator it = targets.iterator(); it.hasNext(); ) {
            EventValue ev = EventFactory.convertToEventValue(it.next());
            String id = ev.getContent();
            if (ev.getType() == Type.EXPR) {
                id = eval(ev.getContent()) + "";
            }
            setAttributeValue(id, value);
        }
    }
    if (be != null && be.getSource() instanceof JavaScriptObject) {
        JavaScriptObject func = (JavaScriptObject) be.getSource();
        invokeFunction(func, value);
    }
}
Example 42
Project: GoFullScreen-master  File: FSNativeButtonConnector.java View source code
@Override
public void onClick(ClickEvent event) {
    if (!FSNativeButtonConnector.this.isEnabled()) {
        LOGGER.fine("Ignoring click when not enabled.");
        return;
    }
    JavaScriptObject target = getTargetElement();
    if (FSButtonUtil.isInFullScreenMode(target)) {
        // LOGGER.fine("FullScreen: toogle off");
        FSButtonUtil.cancelFullScreen();
        notifyStateChange();
    } else {
        // LOGGER.fine("FullScreen: toogle on");
        FSButtonUtil.requestFullScreen(target, BrowserInfo.get().isSafari());
        notifyStateChange();
    }
}
Example 43
Project: gwt-charts-master  File: ArrayHelper.java View source code
/**
	 * Converts a java object array into a mixed javascript array (JsArrayMixed).
	 * 
	 * @param array the array containing values
	 * @return a corresponding JsArrayMixed
	 */
public static JsArrayMixed createArray(Object... array) {
    JsArrayMixed jsArray = JavaScriptObject.createArray().cast();
    for (int i = 0; i < array.length; i++) {
        Object object = array[i];
        if (object == null) {
            jsArray.set(i, (String) null);
        } else if (object instanceof Integer) {
            arraySet(jsArray, i, ((Integer) object).intValue());
        } else if (object instanceof Double) {
            arraySet(jsArray, i, ((Double) object).doubleValue());
        } else if (object instanceof String) {
            arraySet(jsArray, i, (String) object);
        } else if (object instanceof Date) {
            jsArray.set(i, DateHelper.getJsDate((Date) object));
        } else if (object instanceof JavaScriptObject) {
            jsArray.set(i, (JavaScriptObject) object);
        } else {
            throw new RuntimeException("invalid value type");
        }
    }
    return jsArray;
}
Example 44
Project: gwt-node-master  File: JavaScriptUtils.java View source code
public static void addToArray(JsArrayMixed array, Object value) {
    if (value == null) {
        array.push((JavaScriptObject) null);
    } else if (value instanceof Boolean) {
        array.push((Boolean) value);
    } else if (value instanceof Integer) {
        array.push((Integer) value);
    } else if (value instanceof Double) {
        array.push((Double) value);
    } else if (value instanceof Float) {
        array.push((Float) value);
    } else if (value instanceof Byte) {
        array.push((Byte) value);
    } else if (value instanceof Character) {
        array.push((Character) value);
    } else if (value instanceof Short) {
        array.push((Short) value);
    } else if (value instanceof String) {
        array.push((String) value);
    } else if (value instanceof JavaScriptObject) {
        array.push((JavaScriptObject) value);
    } else {
        array.push("" + value);
    }
}
Example 45
Project: gwt-rest-master  File: JsonpMethod.java View source code
@Override
public Object send(final JsonCallback callback) {
    return jsonpBuilder.requestObject(resource.getUri(), new AsyncCallback<JavaScriptObject>() {

        @Override
        public void onSuccess(JavaScriptObject result) {
            callback.onSuccess(JsonpMethod.this, new JSONObject(result));
        }

        @Override
        public void onFailure(Throwable caught) {
            callback.onFailure(JsonpMethod.this, caught);
        }
    });
}
Example 46
Project: html5gwt-master  File: MediaTest.java View source code
@Override
public void onLoad(ArrayBuffer buffer) {
    OfflineAudioContext context = OfflineAudioContext.create(1, 100, 48000);
    final ScriptProcessorNode processor = context.createScriptProcessor(100, 1, 1);
    processor.connect(context.getDestination());
    index = 0;
    context.setOnComplete(new CompleteListener() {

        @Override
        public void onComplete() {
            HTML5Test.log("index:" + index);
        }
    });
    processor.setOnAudioprocess(new AudioProcessingEventListener() {

        @Override
        public void onAudioProcess(AudioProcessingEvent event) {
            if (index < 5) {
                HTML5Test.log(event);
            }
            index++;
        //HTML5Test.log(""+index);
        }
    });
    //context.crea
    context.decodeAudioData(new DecodeAudioListener() {

        @Override
        public void onDecode(ArrayBuffer decodeBuffer) {
            HTML5Test.log(Uint8Array.createUint8(decodeBuffer));
        }
    }, new DecodeErrorListener() {

        @Override
        public void onError(JavaScriptObject error) {
            HTML5Test.log(error);
        }
    });
}
Example 47
Project: ide-master  File: EditorPreferenceReader.java View source code
/**
     * Retrieves the editor preference object as stored in the preference json string.
     * @return the preference object or null
     */
private EditorPreferences getPreferencesOrNull() {
    final String prefAsJson = this.preferencesManager.getValue(PREFERENCE_PROPERTY);
    if (prefAsJson == null || prefAsJson.isEmpty()) {
        return null;
    }
    JSONValue propertyObject;
    try {
        final JSONValue parseResult = JSONParser.parseStrict(prefAsJson);
        propertyObject = parseResult.isObject();
    } catch (final RuntimeException e) {
        Log.error(KeymapPrefReader.class, "Error during preference parsing.", e);
        return null;
    }
    if (propertyObject == null) {
        return null;
    }
    JavaScriptObject propertyValue;
    try {
        propertyValue = propertyObject.isObject().getJavaScriptObject();
    } catch (final RuntimeException e) {
        Log.error(KeymapPrefReader.class, "Invalid value for editor preference.", e);
        return null;
    }
    return propertyValue.cast();
}
Example 48
Project: JsonDdl-master  File: GwtTestExample.java View source code
@Test
public void test() {
    Example e = JavaScriptObject.createObject().cast();
    e.setABoolean(true);
    e.setAnExample(JavaScriptObject.createObject().<Example>cast());
    e.setAnExampleList(JavaScriptObject.createArray().<JsArray<Example>>cast());
    e.setAnIntegralList(JavaScriptObject.createArray().<JsArrayInteger>cast());
    e.setAString("Hello world!");
    e.setDouble(42.2);
    e.setInt(42);
    MapIsh<JsArrayBoolean> mapish = JavaScriptObject.createObject().cast();
    mapish.put("Hello", JavaScriptObject.createArray().<JsArrayBoolean>cast());
    e.setAStringToListOfBooleanMap(mapish);
    assertEquals("{\"aBoolean\":true,\"anExample\":{},\"anExampleList\":[],\"anIntegralList\":[]," + "\"aString\":\"Hello world!\",\"double\":42.2,\"int\":42," + "\"aStringToListOfBooleanMap\":{\"Hello\":[]}}", stringify(e));
}
Example 49
Project: mini-git-server-master  File: Edit_JsonSerializer.java View source code
@Override
public Edit fromJson(Object jso) {
    if (jso == null) {
        return null;
    }
    final JavaScriptObject o = (JavaScriptObject) jso;
    final int cnt = length(o);
    if (4 == cnt) {
        return new Edit(get(o, 0), get(o, 1), get(o, 2), get(o, 3));
    }
    List<Edit> l = new ArrayList<Edit>((cnt / 4) - 1);
    for (int i = 4; i < cnt; ) {
        int as = get(o, i++);
        int ae = get(o, i++);
        int bs = get(o, i++);
        int be = get(o, i++);
        l.add(new Edit(as, ae, bs, be));
    }
    return new ReplaceEdit(get(o, 0), get(o, 1), get(o, 2), get(o, 3), l);
}
Example 50
Project: resty-gwt-master  File: JsonpMethod.java View source code
@Override
public Object send(final JsonCallback callback) {
    return jsonpBuilder.requestObject(resource.getUri(), new AsyncCallback<JavaScriptObject>() {

        @Override
        public void onSuccess(JavaScriptObject result) {
            callback.onSuccess(JsonpMethod.this, new JSONObject(result));
        }

        @Override
        public void onFailure(Throwable caught) {
            callback.onFailure(JsonpMethod.this, caught);
        }
    });
}
Example 51
Project: sigmah-master  File: SpecificObjectiveJS.java View source code
public void setExpectedResults(List<ExpectedResultDTO> expectedResults) {
    if (expectedResults != null) {
        final JsArray<ExpectedResultJS> array = (JsArray<ExpectedResultJS>) JavaScriptObject.createArray();
        for (final ExpectedResultDTO expectedResult : expectedResults) {
            array.push(ExpectedResultJS.toJavaScript(expectedResult));
        }
        setExpectedResults(array);
    }
}
Example 52
Project: TheSocialOS-master  File: DriveAPI.java View source code
@Override
public void onSuccess(JavaScriptObject result) {
    JSONObject js = new JSONObject(result);
    // Window.alert(js.toString());
    JSONArray array = js.get("feed").isObject().get("entry").isArray();
    HashSet<DriveAPI.File> files = new HashSet<DriveAPI.File>();
    // Window.alert(array.size() + "");
    for (int i = 0; i < array.size(); i++) {
        JSONObject parentLink = array.get(i).isObject().get("link").isArray().get(0).isObject();
        if (parentLink.get("rel").isString().stringValue().contains("parent")) {
            String id = array.get(i).isObject().get("id").isObject().get("$t").isString().stringValue();
            String title = array.get(i).isObject().get("title").isObject().get("$t").isString().stringValue();
            String parentName = parentLink.get("title").isString().stringValue();
            files.add(new File(id, title, parentName));
        }
    }
    folder.addMedia(files);
// loadFilesInFolder(files);
}
Example 53
Project: tools_gerrit-master  File: Edit_JsonSerializer.java View source code
@Override
public Edit fromJson(Object jso) {
    if (jso == null) {
        return null;
    }
    final JavaScriptObject o = (JavaScriptObject) jso;
    final int cnt = length(o);
    if (4 == cnt) {
        return new Edit(get(o, 0), get(o, 1), get(o, 2), get(o, 3));
    }
    List<Edit> l = new ArrayList<Edit>((cnt / 4) - 1);
    for (int i = 4; i < cnt; ) {
        int as = get(o, i++);
        int ae = get(o, i++);
        int bs = get(o, i++);
        int be = get(o, i++);
        l.add(new Edit(as, ae, bs, be));
    }
    return new ReplaceEdit(get(o, 0), get(o, 1), get(o, 2), get(o, 3), l);
}
Example 54
Project: uberfire-master  File: SplashScreenJSExporter.java View source code
public static void registerSplashScreen(final Object _obj) {
    final JavaScriptObject obj = (JavaScriptObject) _obj;
    if (JSNativeSplashScreen.hasStringProperty(obj, "id") && JSNativeSplashScreen.hasTemplate(obj)) {
        final SyncBeanManager beanManager = IOC.getBeanManager();
        final ActivityBeansCache activityBeansCache = beanManager.lookupBean(ActivityBeansCache.class).getInstance();
        final JSNativeSplashScreen newNativePlugin = beanManager.lookupBean(JSNativeSplashScreen.class).getInstance();
        newNativePlugin.build(obj);
        final SplashView splashView = beanManager.lookupBean(SplashView.class).getInstance();
        JSSplashScreenActivity activity = JSExporterUtils.findActivityIfExists(beanManager, newNativePlugin.getId(), JSSplashScreenActivity.class);
        if (activity == null) {
            registerNewActivity(beanManager, activityBeansCache, newNativePlugin, splashView);
        } else {
            updateExistentActivity(newNativePlugin, activity);
        }
    }
}
Example 55
Project: Wave-master  File: TemplateNodeMutationHandler.java View source code
/**
   * Creates a renderer for <template> doodads.
   */
static TemplateNodeMutationHandler create() {
    final PartIdFactory partIdFactory = SessionPartIdFactory.get();
    CajolerFacade cajoler = CajolerFacade.instance();
    final JavaScriptObject taming = cajoler.getTaming();
    PluginContextFactory defaultFactory = new PluginContextFactory() {

        @Override
        public PluginContext create(ContentElement doodad) {
            return new PluginContext(doodad, partIdFactory, taming);
        }
    };
    return new TemplateNodeMutationHandler(cajoler, defaultFactory);
}
Example 56
Project: wave-protocol-master  File: TemplateNodeMutationHandler.java View source code
/**
   * Creates a renderer for <template> doodads.
   */
static TemplateNodeMutationHandler create() {
    final PartIdFactory partIdFactory = SessionPartIdFactory.get();
    CajolerFacade cajoler = CajolerFacade.instance();
    final JavaScriptObject taming = cajoler.getTaming();
    PluginContextFactory defaultFactory = new PluginContextFactory() {

        @Override
        public PluginContext create(ContentElement doodad) {
            return new PluginContext(doodad, partIdFactory, taming);
        }
    };
    return new TemplateNodeMutationHandler(cajoler, defaultFactory);
}
Example 57
Project: WaveInCloud-master  File: TemplateNodeMutationHandler.java View source code
/**
   * Creates a renderer for <template> doodads.
   */
static TemplateNodeMutationHandler create() {
    final PartIdFactory partIdFactory = SessionPartIdFactory.get();
    CajolerFacade cajoler = CajolerFacade.instance();
    final JavaScriptObject taming = cajoler.getTaming();
    PluginContextFactory defaultFactory = new PluginContextFactory() {

        @Override
        public PluginContext create(ContentElement doodad) {
            return new PluginContext(doodad, partIdFactory, taming);
        }
    };
    return new TemplateNodeMutationHandler(cajoler, defaultFactory);
}
Example 58
Project: actor-platform-master  File: PeerConnection.java View source code
@Override
public void exec(@NotNull final PromiseResolver<WebRTCSessionDescription> resolver) {
    peerConnection.setRemoteDescription(JsSessionDescription.create(description.getType(), description.getSdp()), new JsClosure() {

        @Override
        public void callback() {
            resolver.result(description);
        }
    }, new JsClosureError() {

        @Override
        public void onError(JavaScriptObject error) {
            resolver.error(new JavaScriptException(error));
        }
    });
}
Example 59
Project: bi-platform-v2-master  File: GwtDatasourceEditorEntryPoint.java View source code
/**
   * Entry-point from Javascript, responds to provided callback with the following:
   *
   *    onOk(String JSON, String mqlString);
   *    onCancel();
   *    onError(String errorMessage);
   *
   * @param callback
   *
   */
private void show(final JavaScriptObject callback) {
    final DialogListener<Domain> listener = new DialogListener<Domain>() {

        public void onDialogCancel() {
            notifyCallbackCancel(callback);
        }

        public void onDialogAccept(final Domain domain) {
            WAQRTransport transport = WAQRTransport.createFromMetadata(domain);
            notifyCallbackSuccess(callback, true, transport);
        }

        public void onDialogReady() {
            notifyCallbackReady(callback);
        }
    };
    editor.addDialogListener(listener);
    editor.showDialog();
}
Example 60
Project: BVH-Pose-Editor-master  File: PoseEditorDataConverter.java View source code
/**
	 * TODO set name and cdate by yourself
	 */
@Override
protected JSONObject doForward(BVH bvh) {
    List<BVHNode> nodes = bvh.getNodeList();
    //for find Index
    List<String> boneNameList = new ArrayList<String>();
    JsArrayString boneNames = (JsArrayString) JsArrayString.createArray();
    for (BVHNode node : nodes) {
        boneNames.push(node.getName());
        boneNameList.add(node.getName());
    }
    List<NameAndChannel> channels = bvh.getNameAndChannels();
    JsArray<JavaScriptObject> frames = (JsArray<JavaScriptObject>) JsArray.createArray();
    for (int i = 0; i < bvh.getFrames(); i++) {
        //re create FrameData 
        JsArray<JsArrayNumber> positions = (JsArray<JsArrayNumber>) JsArray.createArray();
        JsArray<JsArrayNumber> rots = (JsArray<JsArrayNumber>) JsArray.createArray();
        for (int j = 0; j < boneNameList.size(); j++) {
            JsArrayNumber pos = (JsArrayNumber) JsArrayNumber.createArray();
            pos.push(0);
            pos.push(0);
            pos.push(0);
            positions.push(pos);
            JsArrayNumber rot = (JsArrayNumber) JsArrayNumber.createArray();
            rot.push(0);
            rot.push(0);
            rot.push(0);
            rots.push(rot);
        }
        //must same channels size
        double[] values = bvh.getFrameAt(i);
        int valueIndex = 0;
        for (NameAndChannel channel : channels) {
            int index = boneNameList.indexOf(channel.getName());
            if (index == -1) {
                LogUtils.log("not found:maybe invalid-channel:" + channel.getName());
                continue;
            }
            boolean targetPos = false;
            int targetIndex = 0;
            switch(channel.getChannel()) {
                case Channels.XPOSITION:
                    targetPos = true;
                    targetIndex = 0;
                    break;
                case Channels.YPOSITION:
                    targetPos = true;
                    targetIndex = 1;
                    break;
                case Channels.ZPOSITION:
                    targetPos = true;
                    targetIndex = 2;
                    break;
                case Channels.XROTATION:
                    targetPos = false;
                    targetIndex = 0;
                    break;
                case Channels.YROTATION:
                    targetPos = false;
                    targetIndex = 1;
                    break;
                case Channels.ZROTATION:
                    targetPos = false;
                    targetIndex = 2;
                    break;
                default:
                    LogUtils.log("invalid type:" + channel.getChannel());
            }
            if (targetPos) {
                positions.get(index).set(targetIndex, values[valueIndex]);
            } else {
                rots.get(index).set(targetIndex, values[valueIndex]);
            }
            valueIndex++;
        }
        JSONObject frame = new JSONObject();
        frame.put("angles", new JSONArray(rots));
        frame.put("positions", new JSONArray(positions));
        frames.push(frame.getJavaScriptObject());
    }
    JSONObject jsonObject = new JSONObject();
    jsonObject.put("frames", new JSONArray(frames));
    jsonObject.put("bones", new JSONArray(boneNames));
    return jsonObject;
}
Example 61
Project: exo-training-master  File: WSDLWebServiceSample.java View source code
public void callService() {
    if (zipCodeService == null) {
        SC.say("Please try again in a moment  - still loading web service descriptor");
    } else {
        setValue("City", "Loading...");
        Map data = new LinkedHashMap();
        data.put("USZip", getValueAsString("ZipCode"));
        zipCodeService.callOperation("GetInfoByZIP", data, "//CITY", new WebServiceCallback() {

            public void execute(Object[] data, JavaScriptObject xmlDoc, RPCResponse rpcResponse, JavaScriptObject wsRequest) {
                ZipForm.this.setValue("City", (String) data[0]);
            }
        });
    }
}
Example 62
Project: geogebra-master  File: WindowReference.java View source code
private static JavaScriptObject createWindowReference(String name, String redirect, String callback, int width, int height) {
    int left = (Window.getClientWidth() / 2) - (width / 2);
    int top = (Window.getClientHeight() / 2) - (height / 2);
    return WindowW.open(BASEURL.getOpenerUrl() + "?redirect=" + redirect + "&callback=" + callback, name, "resizable," + "toolbar=no," + "location=no," + "scrollbars=no, " + "statusbar=no, " + "titlebar=no, " + "width=" + width + "," + "height=" + height + "," + "left=" + left + ", " + "top=" + top);
}
Example 63
Project: google-apis-explorer-master  File: DynamicJsoGwtTest.java View source code
/** Array of keys is accessible through the JSO. */
public void testDynamicJso_keys() {
    DynamicJso jso = JsonUtils.safeEval("{\"a\":{\"foo\":\"bar\"}}");
    assertEquals(1, jso.keys().length());
    assertEquals("a", jso.keys().get(0));
    jso = JavaScriptObject.createObject().cast();
    jso.set("a", true);
    jso.set("b", false);
    jso.set("c", 123);
    assertEquals(3, jso.keys().length());
    assertEquals("a", jso.keys().get(0));
    assertEquals("b", jso.keys().get(1));
    assertEquals("c", jso.keys().get(2));
    // Getting a non-existent key return null
    assertNull(jso.get("zzz"));
    assertNull(jso.typeofKey("zzz"));
}
Example 64
Project: gwt-jackson-master  File: JavaScriptObjectGwtTest.java View source code
public void testRootJsArrayString() {
    JsArrayString array = JavaScriptObject.createArray().cast();
    array.push("Hello");
    array.push("World");
    array.push("!");
    String json = JsArrayStringMapper.INSTANCE.write(array);
    assertEquals("[\"Hello\",\"World\",\"!\"]", json);
    array = JsArrayStringMapper.INSTANCE.read(json);
    assertEquals(3, array.length());
    assertEquals("Hello", array.get(0));
    assertEquals("World", array.get(1));
    assertEquals("!", array.get(2));
}
Example 65
Project: GWT-Maps-V3-Api-master  File: FusionTablesMapWidget.java View source code
public void onEvent(FusionTablesMouseMapEvent event) {
    @SuppressWarnings("unused") String infoWindowHtml = event.getInfoWindowHtml();
    LatLng latlng = event.getLatLng();
    @SuppressWarnings("unused") Size pixelOffset = event.getPixelOffset();
    @SuppressWarnings("unused") JavaScriptObject jso = event.getRow();
    String json = event.getRowAsJson();
    GWT.log("click on " + latlng.getToString() + "  json=" + json);
}
Example 66
Project: gwt-tictactoe-master  File: PhotoMap.java View source code
public static HashMap<String, Photo> getStorageMap(Storage storage, Key key) {
    Log.info("::getFromStorage");
    String json = storage.getItem(key.getName());
    HashMap map = new HashMap<String, Photo>();
    if (json == null || json.trim().length() < 1) {
        return map;
    }
    JsArray<? extends JavaScriptObject> j = JsonUtils.safeEval(json);
    ArrayList<Photo> data = JsUtils.toArray(j);
    for (Photo u : data) {
        map.put(u.getUrl(), u);
    }
    return map;
}
Example 67
Project: gwtbootstrap3-master  File: Popover.java View source code
/** [email protected]} */
@Override
public void init() {
    Element element = getWidget().getElement();
    JavaScriptObject baseOptions = createOptions(element, isAnimated(), isHtml(), getSelector(), getTrigger().getCssName(), getShowDelayMs(), getHideDelayMs(), getContainer(), prepareTemplate(), getViewportSelector(), getViewportPadding());
    popover(element, baseOptions, getContent());
    bindJavaScriptEvents(element);
    setInitialized(true);
}
Example 68
Project: gwtquery-master  File: JsonBuilderBase.java View source code
protected <T> void setArrayBase(String n, T[] r) {
    if (r.length > 0 && r[0] instanceof JsonBuilder) {
        JsArray<JavaScriptObject> a = JavaScriptObject.createArray().cast();
        for (T o : r) {
            a.push(((JsonBuilder) o).<Properties>getDataImpl());
        }
        p.set(n, a);
    } else {
        JsObjectArray<Object> a = JsObjectArray.create();
        a.add(r);
        p.set(n, a);
    }
}
Example 69
Project: GXT_RTL-master  File: ColorPalette.java View source code
@Override
protected void onRender(Element target, int index) {
    setElement(DOM.createDiv(), target, index);
    super.onRender(target, index);
    if (template == null) {
        String html = "<tpl for=\".\"><a href=\"#\" class=\"color-{.}\"><em><span style=\"background:#{.}\" unselectable=\"on\"> </span></em></a></tpl>";
        setTemplate(XTemplate.create(html));
    }
    JavaScriptObject toJavaScriptArray = JsUtil.toJavaScriptArray(getColors());
    getTemplate().overwrite(el().dom, toJavaScriptArray);
    sinkEvents(Event.ONCLICK | Event.ONMOUSEOVER | Event.ONMOUSEOUT);
}
Example 70
Project: horaz-master  File: AsynchronousDataStore.java View source code
@Override
public K next() {
    if (!hasNext())
        return null;
    JavaScriptObject jsObj = data.getRows().getItem(cursor++);
    K mdl = parent.reflectJavaScriptObject(jsObj);
    if (joinedDataStore != null) {
        mdl.setJoinedModel(joinedDataStore.reflectJavaScriptObject(jsObj));
    }
    // store children count
    parent.storeChildrenCount(mdl, jsObj);
    return mdl;
}
Example 71
Project: htmlparser-master  File: HtmlParserModule.java View source code
@SuppressWarnings("unused")
private static void parseHtmlDocument(String source, JavaScriptObject document, JavaScriptObject readyCallback, JavaScriptObject errorHandler) throws SAXException {
    if (readyCallback == null) {
        readyCallback = JavaScriptObject.createFunction();
    }
    zapChildren(document);
    HtmlParser parser = new HtmlParser(document);
    parser.setScriptingEnabled(true);
    // XXX error handler
    installDocWrite(document, parser);
    parser.parse(source, new ParseEndListener(readyCallback));
}
Example 72
Project: incubator-wave-master  File: TemplateNodeMutationHandler.java View source code
/**
   * Creates a renderer for <template> doodads.
   */
static TemplateNodeMutationHandler create() {
    final PartIdFactory partIdFactory = SessionPartIdFactory.get();
    CajolerFacade cajoler = CajolerFacade.instance();
    final JavaScriptObject taming = cajoler.getTaming();
    PluginContextFactory defaultFactory = new PluginContextFactory() {

        @Override
        public PluginContext create(ContentElement doodad) {
            return new PluginContext(doodad, partIdFactory, taming);
        }
    };
    return new TemplateNodeMutationHandler(cajoler, defaultFactory);
}
Example 73
Project: objectfabric-master  File: IndexedDBQueue.java View source code
final void write(JavaScriptObject transaction, URI uri, long tick, Buff[] buffs, long[] removals, boolean callback) {
    IndexedDBView view = (IndexedDBView) uri.getOrCreate(_location);
    ArrayBuffer buffer = null;
    if (buffs.length == 1) {
        GWTBuff buff = (GWTBuff) buffs[0];
    //          buffer = buff.slice();
    } else {
        int capacity = 0;
        for (int i = 0; i < buffs.length; i++) capacity += buffs[i].remaining();
        Uint8Array array = ((GWTPlatform) Platform.get()).newUint8Array(capacity);
        int position = 0;
        for (int i = 0; i < buffs.length; i++) {
            GWTBuff buff = (GWTBuff) buffs[i];
            array.set(buff.subarray(), position);
            position += buff.remaining();
        }
    //            buffer = array.buffer();
    }
    JavaScriptObject request = write(transaction, IndexedDB.BLOCKS, view.getKey(tick), buffer);
    if (callback)
        callback(request, view, uri, new long[] { tick }, buffs, removals);
    if (removals != null)
        for (int i = 0; i < removals.length; i++) if (!Tick.isNull(removals[i]))
            delete(_location.db(), IndexedDB.BLOCKS, view.getKey(removals[i]));
    _ongoing++;
}
Example 74
Project: osgi-maven-master  File: JsonReader.java View source code
@SuppressWarnings({ "unchecked", "rawtypes" })
public D read(Object loadConfig, Object data) {
    JSONObject jsonRoot = null;
    if (data instanceof JavaScriptObject) {
        jsonRoot = new JSONObject((JavaScriptObject) data);
    } else {
        jsonRoot = (JSONObject) JSONParser.parse((String) data);
    }
    JSONArray root = (JSONArray) jsonRoot.get(modelType.getRoot());
    int size = root.size();
    ArrayList<ModelData> models = new ArrayList<ModelData>();
    for (int i = 0; i < size; i++) {
        JSONObject obj = (JSONObject) root.get(i);
        ModelData model = newModelInstance();
        for (int j = 0; j < modelType.getFieldCount(); j++) {
            DataField field = modelType.getField(j);
            String name = field.getName();
            Class type = field.getType();
            String map = field.getMap() != null ? field.getMap() : field.getName();
            JSONValue value = obj.get(map);
            if (value == null)
                continue;
            if (value.isArray() != null) {
            // nothing
            } else if (value.isBoolean() != null) {
                model.set(name, value.isBoolean().booleanValue());
            } else if (value.isNumber() != null) {
                if (type != null) {
                    Double d = value.isNumber().doubleValue();
                    if (type.equals(Integer.class)) {
                        model.set(name, d.intValue());
                    } else if (type.equals(Long.class)) {
                        model.set(name, d.longValue());
                    } else if (type.equals(Float.class)) {
                        model.set(name, d.floatValue());
                    } else {
                        model.set(name, d);
                    }
                } else {
                    model.set(name, value.isNumber().doubleValue());
                }
            } else if (value.isObject() != null) {
            // nothing
            } else if (value.isString() != null) {
                String s = value.isString().stringValue();
                if (type != null) {
                    if (type.equals(Date.class)) {
                        if ("timestamp".equals(field.getFormat())) {
                            Date d = new Date(Long.parseLong(s) * 1000);
                            model.set(name, d);
                        } else {
                            DateTimeFormat format = DateTimeFormat.getFormat(field.getFormat());
                            Date d = format.parse(s);
                            model.set(name, d);
                        }
                    }
                } else {
                    model.set(name, s);
                }
            } else if (value.isNull() != null) {
                model.set(name, null);
            }
        }
        models.add(model);
    }
    int totalCount = models.size();
    if (modelType.getTotalName() != null) {
        totalCount = getTotalCount(jsonRoot);
    }
    return (D) createReturnData(loadConfig, models, totalCount);
}
Example 75
Project: plugin-editor-codemirror-master  File: HighlighterInitializer.java View source code
public Promise<CodeMirrorOverlay> initModes(final List<String> modes) {
    final String[] baseScripts = new String[] { codemirrorBase + "lib/codemirror", codemirrorBase + "mode/meta", codemirrorBase + "addon/mode/loadmode", codemirrorBase + "addon/scroll/simplescrollbars", codemirrorBase + "addon/scroll/scrollpastend" };
    final List<String> scriptList = new ArrayList<>();
    for (final String script : baseScripts) {
        scriptList.add(script);
    }
    for (final String mode : modes) {
        scriptList.add(codemirrorBase + "mode/" + mode + "/" + mode);
    }
    final Call<JavaScriptObject[], Throwable> requireCall = new Call<JavaScriptObject[], Throwable>() {

        @Override
        public void makeCall(final Callback<JavaScriptObject[], Throwable> callback) {
            requireJsLoader.require(callback, scriptList.toArray(new String[scriptList.size()]));
        }
    };
    final Promise<JavaScriptObject[]> requirePromise = CallbackPromiseHelper.createFromCallback(requireCall);
    requirePromise.then(new Operation<JavaScriptObject[]>() {

        @Override
        public void apply(final JavaScriptObject[] result) throws OperationException {
            LOG.log(Level.INFO, "Obtained codemirror instance with runmode: " + result[0]);
        }
    });
    requirePromise.catchError(new Operation<PromiseError>() {

        @Override
        public void apply(final PromiseError result) throws OperationException {
            LOG.log(Level.SEVERE, "Failed to obtain codemirror instance");
            LOG.fine(result.toString());
        }
    });
    final Promise<CodeMirrorOverlay> highlightPromise = requirePromise.then(new Function<JavaScriptObject[], CodeMirrorOverlay>() {

        @Override
        public CodeMirrorOverlay apply(final JavaScriptObject[] args) throws FunctionException {
            return args[0].cast();
        }
    });
    return highlightPromise;
}
Example 76
Project: proarc-master  File: UserDataSource.java View source code
@Override
protected Object transformRequest(DSRequest dsRequest) {
    DSOperationType op = dsRequest.getOperationType();
    if (op == DSOperationType.ADD || op == DSOperationType.UPDATE) {
        JavaScriptObject data = dsRequest.getData();
        Record nonNulls = ClientUtils.removeNulls(new Record(data));
        dsRequest.setData(nonNulls);
    }
    return super.transformRequest(dsRequest);
}
Example 77
Project: turbogwt-http-master  File: JsonObjectSerdes.java View source code
@Override
public <C extends Collection<T>> C deserializeAsCollection(Class<C> collectionType, String response, DeserializationContext context) {
    if (!isArray(response))
        throw new UnableToDeserializeException("Response content is not an array.");
    C col = getCollectionInstance(context, collectionType);
    @SuppressWarnings("unchecked") JsArray<JavaScriptObject> jsArray = (JsArray<JavaScriptObject>) eval(response);
    for (int i = 0; i < jsArray.length(); i++) {
        JavaScriptObject jso = jsArray.get(i);
        col.add(readJson((JsonRecordReader) jso, context));
    }
    return col;
}
Example 78
Project: vtm-master  File: GeoJsonTileDecoder.java View source code
public boolean decode(Tile tile, ITileDataSink sink, JavaScriptObject jso) {
    mTileDataSink = sink;
    mTileScale = 1 << tile.zoomLevel;
    mTileX = tile.tileX / mTileScale;
    mTileY = tile.tileY / mTileScale;
    mTileScale *= Tile.SIZE;
    FeatureCollection c = (FeatureCollection) jso;
    for (Feature f : c.getFeatures()) {
        mapElement.clear();
        mapElement.tags.clear();
        /* add tag information */
        mTileSource.decodeTags(mapElement, f.getProperties(mProperties));
        if (mapElement.tags.numTags == 0)
            continue;
        /* add geometry information */
        decodeGeometry(f.getGeometry());
        if (mapElement.type == GeometryType.NONE)
            continue;
        mTileDataSink.process(mapElement);
    }
    return true;
}
Example 79
Project: enunciate-master  File: ClientClassnameForMethod.java View source code
@Override
public String convertUnwrappedObject(Object unwrapped) throws TemplateModelException {
    if (unwrapped instanceof Entity) {
        List<? extends MediaTypeDescriptor> mediaTypes = ((Entity) unwrapped).getMediaTypes();
        for (MediaTypeDescriptor mediaType : mediaTypes) {
            if (this.jsonContext.getLabel().equals(mediaType.getSyntax())) {
                DataTypeReference dataType = mediaType.getDataType();
                return super.convertUnwrappedObject(this.jsonContext.findType(dataType));
            }
        }
        return "com.google.gwt.core.client.JavaScriptObject";
    }
    return super.convertUnwrappedObject(unwrapped);
}
Example 80
Project: ahome-node-master  File: JavaScriptUtils.java View source code
public static void addToArray(JsArrayMixed array, Object value) {
    if (value == null) {
        array.push((JavaScriptObject) null);
    } else if (value instanceof Boolean) {
        array.push((Boolean) value);
    } else if (value instanceof Integer) {
        array.push((Integer) value);
    } else if (value instanceof Double) {
        array.push((Double) value);
    } else if (value instanceof Float) {
        array.push((Float) value);
    } else if (value instanceof Byte) {
        array.push((Byte) value);
    } else if (value instanceof Character) {
        array.push((Character) value);
    } else if (value instanceof Short) {
        array.push((Short) value);
    } else if (value instanceof String) {
        array.push((String) value);
    } else if (value instanceof JavaScriptObject) {
        array.push((JavaScriptObject) value);
    } else {
        array.push("" + value);
    }
}
Example 81
Project: bonita-web-master  File: IFrameView.java View source code
@Override
protected void onDetach() {
    if (messageEventListeners != null) {
        for (final PostMessageEventListener messageEventListener : messageEventListeners) {
            final JavaScriptObject postMessageListenerFunction = postMessageListenerFunctions.remove(messageEventListener.getActionToWatch());
            removeFrameNotificationListener(postMessageListenerFunction);
        }
    }
    super.onDetach();
}
Example 82
Project: cmestemp22-master  File: CreateOrUpdateEducationPanel.java View source code
/**
     * A Recreates the form.
     * 
     * @param education
     *            The enrollment.
     */
private void createForm(final Enrollment education) {
    this.clear();
    FormBuilder form;
    AutoCompleteItemDropDownFormElement nameOfSchool = new AutoCompleteItemDropDownFormElement("Name of School", "nameOfSchool", "", "", true, "/resources/autocomplete/school_name/", "itemNames", "");
    nameOfSchool.setMaxLength(MAX_LENGTH);
    nameOfSchool.setOnItemSelectedCommand(new AutoCompleteItemDropDownFormElement.OnItemSelectedCommand() {

        public void itemSelected(final JavaScriptObject obj) {
        }
    });
    LinkedList<String> degrees = new LinkedList<String>();
    degrees.add("Select");
    degrees.add("Associate");
    degrees.add("Bachelors");
    degrees.add("Masters");
    degrees.add("Doctorate");
    BasicDropDownFormElement degree;
    AutoCompleteItemDropDownFormElement areaOfStudy = new AutoCompleteItemDropDownFormElement("Area of Study", "areasOfStudy", "", "", true, "/resources/autocomplete/area_of_study/", "itemNames", "");
    areaOfStudy.setMaxLength(MAX_LENGTH);
    areaOfStudy.setOnItemSelectedCommand(new AutoCompleteItemDropDownFormElement.OnItemSelectedCommand() {

        public void itemSelected(final JavaScriptObject obj) {
        }
    });
    IntegerTextBoxFormElement yearGraduated = new IntegerTextBoxFormElement("yyyy", 4, "Year Graduated", "yearGraduated", "", "Currently a student? Enter your expected graduation year.", false);
    BasicTextAreaFormElement additionalDetails = new BasicTextAreaFormElement(MAX_DETAILS, "Additional Details", "additionalDetails", "", "Add any additional comments about your academic studies such as awards, " + "papers authored, honors received, etc.", false);
    if (education == null) {
        form = new FormBuilder("Add School", PersonalEducationModel.getInstance(), Method.INSERT, false);
        degree = new BasicDropDownFormElement("Degree", "degree", degrees, "", "", true);
    } else {
        form = new FormBuilder("Edit School", PersonalEducationModel.getInstance(), Method.UPDATE, false);
        form.addStyleName(StaticResourceBundle.INSTANCE.coreCss().editSchool());
        degree = new BasicDropDownFormElement("Degree", "degree", degrees, education.getDegree(), "", true);
        form.addFormElement(new ValueOnlyFormElement("id", education.getId()));
        nameOfSchool.setValue(education.getSchoolName());
        String areaOfStudyString = education.getAreasOfStudy().toString();
        areaOfStudy.setValue(areaOfStudyString.substring(1, areaOfStudyString.length() - 1));
        if (education.getGradDate() != null) {
            yearGraduated.setValue(Integer.toString(education.getGradDate().getYear() + YEAR_CONVERSION));
        }
        additionalDetails.setValue(education.getAdditionalDetails());
    }
    form.addFormElement(nameOfSchool);
    form.addFormElement(degree);
    form.addFormElement(areaOfStudy);
    form.addFormElement(yearGraduated);
    form.addFormElement(additionalDetails);
    form.addFormDivider();
    form.addOnCancelCommand(new Command() {

        public void execute() {
            if (education == null) {
                Session.getInstance().getEventBus().notifyObservers(new BackgroundEducationAddCanceledEvent());
            } else {
                Session.getInstance().getEventBus().notifyObservers(new BackgroundEducationEditCanceledEvent());
            }
        }
    });
    form.setOnCancelHistoryToken(pageHistoryToken);
    this.add(form);
}
Example 83
Project: Collide-master  File: Log.java View source code
private static void log(Class<?> clazz, LogLevel logLevel, Object... args) {
    String prefix = new StringBuilder(logLevel.toString()).append(" (").append(clazz.getName()).append("): ").toString();
    for (Object o : args) {
        if (o instanceof String) {
            logToDevMode(prefix + (String) o);
            logToBrowser(logLevel, prefix + (String) o);
        } else if (o instanceof Throwable) {
            Throwable t = (Throwable) o;
            logToDevMode(prefix + "(click for stack)", t);
            logToBrowser(logLevel, prefix + ExceptionUtils.getStackTraceAsString(t));
        } else if (o instanceof JavaScriptObject) {
            logToDevMode(prefix + "(JSO, see browser's console log for details)");
            logToBrowser(logLevel, prefix + "(JSO below)");
            logToBrowser(logLevel, o);
        } else {
            logToDevMode(prefix + (o != null ? o.toString() : "(null)"));
            logToBrowser(logLevel, prefix + (o != null ? o.toString() : "(null)"));
        }
    }
}
Example 84
Project: data-access-master  File: JSUIDatasourceService.java View source code
@Override
public final void getIds(XulServiceCallback<List<IDatasourceInfo>> callback) {
    List<IDatasourceInfo> datasourceInfoList = new ArrayList<IDatasourceInfo>();
    JsArray<JavaScriptObject> infos = getDelegateIds(this.datasourceServiceObject);
    for (int i = 0; i < infos.length(); i++) {
        JSDatasourceInfo info = new JSDatasourceInfo(infos.get(i));
        datasourceInfoList.add(new DatasourceInfo(info.getName(), info.getName(), info.getType(), info.isEditable(), info.isRemovable(), info.isImportable(), info.isExportable()));
    }
    callback.success(datasourceInfoList);
}
Example 85
Project: geomajas-project-client-gwt2-master  File: PointerEventsImpl.java View source code
public void doInit() {
    if (supports()) {
        logger.info("PointerEventsImpl.doInit");
        if (bitlessEventDispatchers == null) {
            bitlessEventDispatchers = JavaScriptObject.createObject();
            touches = JavaScriptObject.createArray();
            for (PointerEventType e : PointerEventType.values()) {
                addBitlessDispatcher(e.getType(), bitlessEventDispatchers);
            }
            DOMImplStandard.addBitlessEventDispatchers(bitlessEventDispatchers);
            catchAll(PointerEventType.POINTER_CANCEL.getType(), Document.get().getDocumentElement());
            catchAll(PointerEventType.POINTER_UP.getType(), Document.get().getDocumentElement());
        }
    }
}
Example 86
Project: gwtcc-master  File: JsoEval.java View source code
/**
   * A convenience form of 
   * [email protected] #call(Class, Object, String, Class[], Object...)} for use directly
   * by users in a debugger. This method guesses at the types of the method
   * based on the values of [email protected] args}.
   */
public static Object callEx(Class klass, Object obj, String methodName, Object... args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
    if (args == null) {
        // A single-argument varargs null can come in unboxed  
        args = new Object[] { null };
    }
    if (obj != null) {
        if (!obj.getClass().getName().equals(JSO_IMPL_CLASS)) {
            throw new RuntimeException(obj + " is not a JavaScriptObject.");
        }
    }
    // First check java.lang.Object methods for exact matches
    Method[] methods = Object.class.getMethods();
    nextMethod: for (Method m : methods) {
        if (m.getName().equals(methodName)) {
            Class[] types = m.getParameterTypes();
            if (types.length != args.length) {
                continue;
            }
            for (int i = 0, j = 0; i < args.length; ++i, ++j) {
                if (!isAssignable(types[i], args[j])) {
                    continue nextMethod;
                }
            }
            return m.invoke(obj, args);
        }
    }
    ClassLoader ccl = getCompilingClassLoader(klass, obj);
    boolean isJso = isJso(ccl, klass);
    boolean isStaticifiedDispatch = isJso && obj != null;
    int actualNumArgs = isStaticifiedDispatch ? args.length + 1 : args.length;
    ArrayList<Method> matchingMethods = new ArrayList<Method>(Arrays.asList(isJso ? getSisterJsoImpl(klass, ccl).getMethods() : getJsoImplClass(ccl).getMethods()));
    String mangledMethodName = mangleMethod(klass, methodName, isJso, isStaticifiedDispatch);
    // Filter the methods in multiple passes to give better error messages.
    for (Iterator<Method> it = matchingMethods.iterator(); it.hasNext(); ) {
        Method m = it.next();
        if (!m.getName().equalsIgnoreCase(mangledMethodName)) {
            it.remove();
        }
    }
    if (matchingMethods.isEmpty()) {
        throw new RuntimeException("No methods by the name, " + methodName + ", could be found in " + klass);
    }
    ArrayList<Method> candidates = new ArrayList<Method>(matchingMethods);
    for (Iterator<Method> it = matchingMethods.iterator(); it.hasNext(); ) {
        Method m = it.next();
        if (m.getParameterTypes().length != actualNumArgs) {
            it.remove();
        }
    }
    if (matchingMethods.isEmpty()) {
        throw new RuntimeException("No methods by the name, " + methodName + ", in " + klass + " accept " + args.length + " parameters. Candidates are:\n" + candidates);
    }
    candidates = new ArrayList<Method>(matchingMethods);
    nextMethod: for (Iterator<Method> it = matchingMethods.iterator(); it.hasNext(); ) {
        Method m = it.next();
        Class[] methodTypes = m.getParameterTypes();
        for (int i = isStaticifiedDispatch ? 1 : 0, j = 0; i < methodTypes.length; ++i, ++j) {
            if (!isAssignable(methodTypes[i], args[j])) {
                it.remove();
                continue nextMethod;
            }
        }
    }
    if (matchingMethods.isEmpty()) {
        throw new RuntimeException("No methods accepting " + Arrays.asList(args) + " were found for, " + methodName + ", in " + klass + ". Candidates:\n" + candidates);
    }
    candidates = new ArrayList<Method>(matchingMethods);
    if (matchingMethods.size() > 1) {
        // methods by same name but different case.
        for (Iterator<Method> it = matchingMethods.iterator(); it.hasNext(); ) {
            Method m = it.next();
            if (!m.getName().equals(mangledMethodName)) {
                it.remove();
            }
        }
    }
    if (matchingMethods.isEmpty()) {
        throw new RuntimeException("Multiple methods with a case-insensitive match were found for, " + methodName + ", in " + klass + ". Candidates:\n" + candidates);
    }
    if (matchingMethods.size() > 1) {
        throw new RuntimeException("Found more than one matching method. Please specify the types of the parameters. " + "Candidates:\n" + matchingMethods);
    }
    return invoke(klass, obj, matchingMethods.get(0), args);
}
Example 87
Project: Hello-Maps-master  File: EarthPluginDemo.java View source code
public void onEarthInstance(EarthInstanceEvent event) {
    final JavaScriptObject earth = event.getEarthInstance();
    if (earth == null) {
        Window.alert("Failed to init earth plugin");
    } else {
        /*
           * Create a marker. The timer is set to give the earth plugin a chance
           * to position to the proper point on the map.
           */
        new Timer() {

            @Override
            public void run() {
                createPlacemark(earth);
            }
        }.schedule(1000);
    }
}
Example 88
Project: iambookmaster-master  File: FileExchangeClient.java View source code
public String loadFile(String title) {
    try {
        if (checkApplet() == false) {
            return null;
        }
        JavaScriptObject app = getApplet();
        String res = selectFileApplet(app, false, title);
        if (res.equals("OK")) {
            String file = getData(app);
            res = loadFileApplet(file, app);
            if (res.equals("OK")) {
                return getData(app);
            }
        } else if (res != null) {
            Window.alert(res);
        }
    } catch (Exception e) {
        Window.alert(e.getMessage());
    }
    return null;
}
Example 89
Project: kie-wb-common-master  File: DocumentFieldRendererViewImpl.java View source code
public void onSubmit(String results) {
    initForm();
    JavaScriptObject jsResponse = JsonUtils.safeEval(results);
    if (jsResponse != null) {
        JSONObject response = new JSONObject(jsResponse);
        if (response.get("document") != null) {
            JSONObject document = response.get("document").isObject();
            DocumentData data = new DocumentData(document.get("fileName").isString().stringValue(), new Double(document.get("size").isNumber().doubleValue()).longValue(), null);
            data.setContentId(document.get("contentId").isString().stringValue());
            setValue(data, true);
        } else if (response.get("error").isNull() != null) {
            setValue(null, true);
        }
    }
}
Example 90
Project: kune-master  File: WaveMock.java View source code
public void initRandomParticipants() {
    // init some viewer and add it
    ParticipantMock p = JavaScriptObject.createObject().cast();
    p.setupMock();
    p.setDisplayName("Robin the Simple");
    p.setId("1a");
    p.setThumbnailUrl(GWT.getModuleBaseURL() + "robin.jpg");
    participants.push(p);
    // init some host and add it 50% of the time
    ParticipantMock h = JavaScriptObject.createObject().cast();
    h.setupMock();
    h.setDisplayName("Batman the Host");
    h.setId("2b");
    h.setThumbnailUrl(GWT.getModuleBaseURL() + "/batman.jpg");
    participants.push(h);
    viewer = Random.nextBoolean() ? p : h;
    host = Random.nextBoolean() ? h : p;
    eventBus.fireEvent(new ParticipantUpdateEvent(this));
}
Example 91
Project: motiver_fi-master  File: ServerConnection.java View source code
public void onSuccess(JavaScriptObject feed) {
    JSONObject json = null;
    try {
        json = new JSONObject(feed);
        if (!isCancelled) {
            handler.loadOk(json);
        }
    } catch (Exception e) {
        if (!isCancelled) {
            handler.loadError(e);
        }
    }
    Connections.remove(thisCon);
}
Example 92
Project: OneSwarm-master  File: ExternalTextResourcePrototype.java View source code
public void onResponseReceived(Request request, final Response response) {
    // Get the contents of the JSON bundle
    String responseText = response.getText();
    // Call eval() on the object.
    JavaScriptObject jso = evalObject(responseText);
    if (jso == null) {
        callback.onError(new ResourceException(ExternalTextResourcePrototype.this, "eval() returned null"));
        return;
    }
    // Populate the TextResponse cache array
    for (int i = 0; i < cache.length; i++) {
        final String resourceText = extractString(jso, i);
        cache[i] = new TextResource() {

            public String getName() {
                return name;
            }

            public String getText() {
                return resourceText;
            }
        };
    }
    // Finish by invoking the callback
    callback.onSuccess(cache[index]);
}
Example 93
Project: platform-api-client-gwt-master  File: GwtReflectionUtils.java View source code
public static <T> T callPrivateMethod(Object target, String methodName, Object... args) {
    if (target instanceof JavaScriptObject) {
        throw new UnsupportedOperationException("Cannot call instance method on Overlay types without specifying its base type");
    }
    Method method = findMethod(target.getClass(), methodName, args);
    if (method == null) {
        throw new RuntimeException("Cannot find method '" + target.getClass().getName() + "." + methodName + "(..)'");
    }
    return (T) callPrivateMethod(target, method, args);
}
Example 94
Project: qafe-platform-master  File: JSNIUtil.java View source code
private static Map<String, Object> resolveJavaMap(JavaScriptObject jsValue) {
    Map<String, Object> value = new HashMap<String, Object>();
    if (jsValue == null) {
        return value;
    }
    JSONObject jsonObject = new JSONObject(jsValue);
    if (jsonObject.isObject() == null) {
        return value;
    }
    value = resolveJavaMap(jsonObject);
    return value;
}
Example 95
Project: SASAbusHTML5-master  File: SASAbusDBClientImpl.java View source code
@Override
public void onSuccess(JavaScriptObject result) {
    times[i[0]++] = System.currentTimeMillis();
    SASAbusBackendUnmarshaller unmarshaller = new SASAbusBackendUnmarshaller();
    times[i[0]++] = System.currentTimeMillis();
    JSONObject jsonObject = new JSONObject(result);
    GWTStructure gwtStructure = new GWTStructure(jsonObject);
    try {
        times[i[0]++] = System.currentTimeMillis();
        Object obj = unmarshaller.newInstance(unmarshallerRootClassSimpleName);
        times[i[0]++] = System.currentTimeMillis();
        unmarshaller.unmarschall(gwtStructure, obj);
        times[i[0]++] = System.currentTimeMillis();
        String report = "";
        for (int k = 0; k < times.length - 1; k++) {
            report += "Time " + k + ": " + (times[k + 1] - times[k]) + "\n";
        }
        callback.ready((T) obj);
    } catch (Exception e) {
        this.onFailure(e);
    }
}
Example 96
Project: Saxon-CE-master  File: SetProperty.java View source code
public TailCall processLeavingTail(XPathContext context) throws XPathException {
    Object content = eval(select, context);
    JavaScriptObject clientObject = (JavaScriptObject) eval(targetObject, context);
    String member = (String) eval(name, context);
    try {
        IXSLFunction.setProperty(clientObject, member, content);
    } catch (Exception e) {
        throw new XPathException("Error setting client-property: " + member + " " + e.getMessage());
    }
    return null;
}
Example 97
Project: touchkit-master  File: TouchKitConnectionStateHandler.java View source code
@Override
public void pushClosed(PushConnection pushConnection, JavaScriptObject response) {
    if (!offlineModeEntrypoint.isOfflineModeEnabled()) {
        super.pushClosed(pushConnection, response);
    } else if (pushConnection.isBidirectional()) {
        offlineModeEntrypoint.dispatch(BAD_RESPONSE);
    } else {
    // don't care about long polling as xhr is used for client -> server
    }
}
Example 98
Project: turbogwt-core-master  File: JsArrays.java View source code
public static <T extends JavaScriptObject> T[] toArray(JsArray<? extends T> values) {
    if (GWT.isScript()) {
        return reinterpretCast(values);
    } else {
        int length = values.length();
        @SuppressWarnings("unchecked") T[] ret = (T[]) new JavaScriptObject[length];
        for (int i = 0, l = length; i < l; i++) {
            ret[i] = values.get(i);
        }
        return ret;
    }
}
Example 99
Project: VaadinSmartGWT-master  File: VTreeGrid.java View source code
@Override
public void onSelectionUpdated(SelectionUpdatedEvent event) {
    final JavaScriptObject selectedRecordsJSA = toJSOArray(getSelectedRecords());
    JavaScriptObject newExclusionReplacer = JSON.newExclusionReplacer(new String[] { "children", "^_parent_isc_Tree_[0-9]+", "selections", "messages" });
    VTreeGrid.this.client.updateVariable(pid, "selectedRecords", JSON.stringify(selectedRecordsJSA, newExclusionReplacer), false);
}
Example 100
Project: xwiki-platform-master  File: Cache.java View source code
/**
     * Looks up the given key in the cache and returns the associated object if the key if found. Otherwise caches the
     * object returned by the provided call-back and returns it.
     * 
     * @param <T> the type of the cached object
     * @param key the key that identifies the requested object in the cache
     * @param callback the call-back used to retrieve the requested object when it is not found in the cache
     * @return the object associated with the given key in the cache if the cache contains such a key, otherwise the
     *         object returned by the provided call-back
     */
@SuppressWarnings("unchecked")
public <T> T get(String key, CacheCallback<T> callback) {
    org.xwiki.gwt.dom.client.JavaScriptObject map = getMap();
    T object = null;
    if (map != null) {
        object = (T) map.get(key);
    }
    if (object == null) {
        object = callback.get();
        if (map != null) {
            map.set(key, object);
        }
    }
    return object;
}
Example 101
Project: ahome-ace-master  File: AceDemo.java View source code
/**
	 * This is the entry point method.
	 */
public void onModuleLoad() {
    // create first AceEditor widget
    editor1 = new AceEditor();
    editor1.setWidth("800px");
    editor1.setHeight("300px");
    // create second AceEditor widget
    editor2 = new AceEditor();
    editor2.setWidth("800px");
    editor2.setHeight("300px");
    // build the UI
    buildUI();
    // start the first editor and set its theme and mode
    editor1.setTheme(AceEditorTheme.ECLIPSE);
    editor1.setMode(AceEditorMode.JAVA);
    // use cursor position change events to keep a label updated
    // with the current row/col
    editor1.addOnCursorPositionChangeHandler(new AceEditorCallback() {

        @Override
        public void invokeAceCallback(JavaScriptObject obj) {
            updateEditor1CursorPosition();
        }
    });
    // initial update
    updateEditor1CursorPosition();
    // set some initial text in editor 1
    editor1.setText(JAVA_TEXT);
    // add some annotations
    editor1.addAnnotation(0, 1, "What's up?", AceAnnotationType.WARNING);
    editor1.addAnnotation(2, 1, "This code is lame", AceAnnotationType.ERROR);
    editor1.setAnnotations();
    // start the second editor and set its theme and mode
    editor2.setTheme(AceEditorTheme.TWILIGHT);
    editor2.setMode(AceEditorMode.PERL);
}