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: google-web-toolkit-svnmirror-master  File: HasDataPresenterTest.java View source code
public void testCalculateModifiedRanges() {
    HasData<String> listView = new MockHasData<String>();
    MockView<String> view = new MockView<String>();
    HasDataPresenter<String> presenter = new HasDataPresenter<String>(listView, view, 10, null);
    JsArrayInteger rows = JavaScriptObject.createArray().cast();
    // Empty set of rows.
    assertListContains(presenter.calculateModifiedRanges(rows, 0, 10));
    // One row in range.
    rows.push(5);
    assertListContains(presenter.calculateModifiedRanges(rows, 0, 10), new Range(5, 1));
    // One row not in range.
    assertListContains(presenter.calculateModifiedRanges(rows, 6, 10));
    // Consecutive rows (should return only one range).
    rows.push(6);
    rows.push(7);
    rows.push(8);
    assertListContains(presenter.calculateModifiedRanges(rows, 0, 10), new Range(5, 4));
    // Disjoint rows. Should return two ranges.
    rows.push(10);
    rows.push(11);
    assertListContains(presenter.calculateModifiedRanges(rows, 0, 20), new Range(5, 4), new Range(10, 2));
    // Multiple gaps. The largest gap should be between the two ranges.
    rows.push(15);
    rows.push(17);
    assertListContains(presenter.calculateModifiedRanges(rows, 0, 20), new Range(5, 7), new Range(15, 3));
}
Example 2
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 3
Project: crux-master  File: ViewFactoryCreator.java View source code
protected void generateRegisterDataObjectBindersMethod(SourcePrinter printer) {
    printer.println("protected void registerDataObjectBinders(){");
    Iterator<String> dataObjects = bindHandler.iterateDataObjects();
    while (dataObjects.hasNext()) {
        String dataObjectAlias = dataObjects.next();
        String dataObjectClass = context.getDataObjects().getDataObject(dataObjectAlias);
        try {
            JClassType dataObjectType = context.getGeneratorContext().getTypeOracle().getType(dataObjectClass);
            JClassType javaScriptObjectType = context.getGeneratorContext().getTypeOracle().findType(JavaScriptObject.class.getCanonicalName());
            printer.println("addDataObjectBinder(new " + DataObjectBinder.class.getCanonicalName() + "<" + dataObjectClass + ">(this){");
            printer.println("protected " + dataObjectClass + " createDataObject() {");
            if (dataObjectType.isAssignableTo(javaScriptObjectType)) {
                printer.println(dataObjectClass + " obj = " + dataObjectClass + ".createObject().cast();");
                printer.println("return obj;");
            } else {
                printer.println("return GWT.create(" + dataObjectClass + ".class);");
            }
            printer.println("}");
            printer.println("}, " + EscapeUtils.quote(dataObjectAlias) + ");");
        } catch (NotFoundException e) {
            throw new CruxGeneratorException("DataObject class [" + dataObjectClass + "] not found", e);
        }
    }
    printer.println("}");
}
Example 4
Project: framework-master  File: MessageHandler.java View source code
/**
             * Properly clean up any old stuff to ensure everything is properly
             * reinitialized.
             */
private void prepareRepaintAll() {
    String uiConnectorId = getUIConnector().getConnectorId();
    if (uiConnectorId == null) {
        // Nothing to clear yet
        return;
    }
    // Create fake server response that says that the uiConnector
    // has no children
    JsonObject fakeHierarchy = Json.createObject();
    fakeHierarchy.put(uiConnectorId, Json.createArray());
    JsonObject fakeJson = Json.createObject();
    fakeJson.put("hierarchy", fakeHierarchy);
    ValueMap fakeValueMap = ((JavaScriptObject) fakeJson.toNative()).cast();
    // Update hierarchy based on the fake response
    ConnectorHierarchyUpdateResult connectorHierarchyUpdateResult = updateConnectorHierarchy(fakeValueMap);
    // Send hierarchy events based on the fake update
    sendHierarchyChangeEvents(connectorHierarchyUpdateResult.events);
    // Unregister all the old connectors that have now been removed
    unregisterRemovedConnectors(connectorHierarchyUpdateResult.detachedConnectorIds);
}
Example 5
Project: WaveInCloud-master  File: GadgetWidget.java View source code
@Override
public void waveGadgetStateUpdate(final JavaScriptObject delta) {
    // Return if in playback mode. isEditable indicates playback.
    if (!canModifyDocument()) {
        return;
    }
    final StateMap deltaState = StateMap.create();
    deltaState.fromJsonObject(delta);
    // Defer state modifications to avoid RPC failure in Safari 3. The
    // intermittent failure is caused by RPC called from received RPC
    // callback.
    // TODO(user): Remove this workaround once this is fixed in GGS.
    ScheduleCommand.addCommand(new Task() {

        @Override
        public void execute() {
            deltaState.each(new Each() {

                @Override
                public void apply(final String key, final String value) {
                    if (value != null) {
                        modifyState(key, value);
                    } else {
                        deleteState(key);
                    }
                }
            });
            log("Applied delta ", delta.toString(), " new state ", state.toJson());
            gadgetStateSubmitter.triggerScheduledSubmit();
            blipSubmitter.submitImmediately();
        }
    });
}
Example 6
Project: solmix-master  File: SlxRPC.java View source code
public static void send(Roperation oper, final JSCallBack callback) {
    RPCRequest f = new RPCRequest();
    f.setUseSimpleHttp(true);
    String action = SLX_BIN_PREFIX + oper.getOperationType().getValue() + "/" + oper.getDataSource() + SLX_DS_SUFF;
    f.setActionURL(action);
    Request request = new Request(true);
    request.setRoperations(oper);
    f.setData(JSON.encode(request.getJsObj()));
    RPCManager.sendRequest(f, new RPCCallback() {

        @Override
        public void execute(RPCResponse response, Object rawData, RPCRequest request) {
            if (rawData instanceof JavaScriptObject) {
                response.setJavaScriptObject((JavaScriptObject) rawData);
                callback.execute(response, (JavaScriptObject) rawData, request);
            } else {
                JavaScriptObject result = JSOHelper.getAttributeAsJavaScriptObject(JSOHelper.eval(rawData.toString()), "response");
                response.setJavaScriptObject(result);
                callback.execute(response, result, request);
            }
        }
    });
}
Example 7
Project: mini-git-server-master  File: Gerrit.java View source code
static void addHistoryHook(final JavaScriptObject hook) {
    if (historyHooks == null) {
        historyHooks = new ArrayList<JavaScriptObject>();
        History.addValueChangeHandler(new ValueChangeHandler<String>() {

            @Override
            public void onValueChange(ValueChangeEvent<String> event) {
                dispatchHistoryHooks(event.getValue());
            }
        });
    }
    historyHooks.add(hook);
}
Example 8
Project: proarc-master  File: FormGenerator.java View source code
/**
     * Fills a new value of the nested field. It traverses the path of field names
     * to the leaf recursively.
     *
     * @param path path to field; '/' as a separator
     * @param pathIndex field name index in path to update
     * @param pathValue set of attributes of selected field; see pathIndex
     * @param value value to set
     * @return the record with updated attributes or [email protected] null}
     */
private Record fillValueForPath(String[] path, int pathIndex, Object pathValue, String value) {
    Record pathRecord = null;
    // Record[], RecordList, Object[]??
    if (pathValue instanceof JavaScriptObject) {
        JavaScriptObject jso = (JavaScriptObject) pathValue;
        //            ClientUtils.warning(LOG, "## isArray %s", JSOHelper.isArray(jso));
        if (JSOHelper.isArray(jso)) {
        // RecordList ??
        } else {
            pathRecord = new Record(jso);
            // is .../field1/field2 leaf?
            if (pathIndex + 2 == path.length) {
                //                    ClientUtils.warning(LOG, "## vm.setValue %s", path[pathIndex + 1]);
                pathRecord.setAttribute(path[pathIndex + 1], value);
            } else {
                Object nextValueInPath = pathRecord.getAttributeAsObject(path[pathIndex + 1]);
                // recursion
                Record newValueForPath = fillValueForPath(path, pathIndex + 1, nextValueInPath, value);
                if (newValueForPath != null) {
                    pathRecord.setAttribute(path[pathIndex + 1], newValueForPath);
                }
            }
        }
    } else if (pathValue == null) {
        // no value yet; let's create new values for remaining path
        pathRecord = new Record();
        // is .../field1/field2 leaf?
        if (pathIndex + 2 == path.length) {
            //                ClientUtils.warning(LOG, "## vm.setValue %s", path[pathIndex + 1]);
            pathRecord.setAttribute(path[pathIndex + 1], value);
        } else {
            Record newValueForPath = fillValueForPath(path, pathIndex + 1, null, value);
            if (newValueForPath != null) {
                pathRecord.setAttribute(path[pathIndex + 1], newValueForPath);
            } else {
                // unknown new value, do not create anything
                pathRecord = null;
            }
        }
    }
    return pathRecord;
}
Example 9
Project: htmlparser-master  File: BrowserTreeBuilder.java View source code
@Override
protected void addAttributesToElement(JavaScriptObject element, HtmlAttributes attributes) throws SAXException {
    try {
        for (int i = 0; i < attributes.getLength(); i++) {
            String localName = attributes.getLocalNameNoBoundsCheck(i);
            String uri = attributes.getURINoBoundsCheck(i);
            if (!hasAttributeNS(element, uri, localName)) {
                setAttributeNS(element, uri, localName, attributes.getValueNoBoundsCheck(i));
            }
        }
    } catch (JavaScriptException e) {
        fatal(e);
    }
}
Example 10
Project: aokp-gerrit-master  File: PatchSetComplexDisclosurePanel.java View source code
@Override
public void onClick(final ClickEvent event) {
    b.setEnabled(false);
    ChangeApi.deleteChange(patchSet.getId().getParentKey().get(), new GerritCallback<JavaScriptObject>() {

        public void onSuccess(JavaScriptObject result) {
            Gerrit.display(PageLinks.MINE);
        }

        public void onFailure(Throwable err) {
            if (SubmitFailureDialog.isConflict(err)) {
                new SubmitFailureDialog(err.getMessage()).center();
                Gerrit.display(PageLinks.MINE);
            } else {
                b.setEnabled(true);
                super.onFailure(err);
            }
        }
    });
}
Example 11
Project: xapi-master  File: WebComponentFactoryGenerator.java View source code
@Override
public RebindResult generateIncrementally(final TreeLogger logger, final GeneratorContext context, final String typeName) throws UnableToCompleteException {
    final JClassType type = context.getTypeOracle().findType(typeName);
    final WebComponent component = type.getAnnotation(WebComponent.class);
    final Fifo<ShadowDomStyle> styles = extractSharedStyles(type);
    if (component == null) {
        logger.log(Type.ERROR, "Type " + type.getQualifiedSourceName() + " missing required annotation, " + WebComponent.class.getName());
        throw new UnableToCompleteException();
    }
    if (component.tagName().indexOf('-') == -1) {
        logger.log(Type.ERROR, "WebComponent for " + type.getQualifiedSourceName() + " has invalid tag name " + component.tagName() + "; " + "Custom elements must contain the - character");
        throw new UnableToCompleteException();
    }
    final String pkg = type.getPackage().getName();
    final String simple = type.getQualifiedSourceName().replace(pkg + ".", "");
    final String factoryName = toFactoryName(simple);
    final String qualifiedName = pkg + "." + factoryName;
    // TODO reenable this once we add strong hashing support to ensure types
    // have not changed.
    // if (context.tryReuseTypeFromCache(qualifiedName)) {
    // return new RebindResult(RebindMode.USE_ALL_CACHED, qualifiedName);
    // }
    final PrintWriter pw = context.tryCreate(logger, pkg, factoryName);
    if (pw == null) {
        logger.log(logLevel(), "Reusing existing class " + qualifiedName);
        return new RebindResult(RebindMode.USE_EXISTING, qualifiedName);
    }
    final SourceBuilder<ContainerMetadata> sourceBuilder = new SourceBuilder<ContainerMetadata>("public final class " + factoryName).setPackage(pkg);
    final ClassBuffer out = sourceBuilder.getClassBuffer().addInterface(WebComponentFactory.class.getCanonicalName() + "<" + simple + ">");
    final String builder = out.addImport(WebComponentBuilder.class);
    final String support = out.addImport(WebComponentSupport.class);
    final String jso = out.addImport(JavaScriptObject.class);
    final String selfType = out.addImport(typeName);
    final String proto = generatePrototypeAccessor(out, component.extendProto(), jso);
    stringType = context.getTypeOracle().findType("java.lang.String");
    webComponentCallback = context.getTypeOracle().findType(WebComponentCallback.class.getName());
    final Multimap<String, MethodData> methods = LinkedHashMultimap.create();
    final boolean hasCallbacks = type.isAssignableTo(webComponentCallback);
    final List<JClassType> flattened = new ArrayList<JClassType>(type.getFlattenedSupertypeHierarchy());
    for (int i = flattened.size(); i-- > 0; ) {
        final JClassType iface = flattened.get(i);
        generateFunctionAccessors(logger, context, iface, methods, hasCallbacks);
    }
    final String supplier = out.addImport(Supplier.class);
    out.createField(supplier + "<" + simple + ">", "ctor").makeStatic().makePrivate();
    // Initialize the web component in a static block
    out.println("static {").indent();
    if (hasCssToInject(type)) {
        final String injectCss = out.addImportStatic("xapi.elemental.X_Elemental.injectCss");
        out.println(injectCss + "(" + selfType + ".class);");
    }
    out.println(builder + " builder = " + builder + ".create(" + proto + ");");
    if (component.extendProto().length > 1) {
        out.println("builder.setExtends(\"" + component.extendProto()[1] + "\");");
    }
    final Set<String> seen = new HashSet<>();
    for (int i = flattened.size(); i-- > 0; ) {
        final JClassType key = flattened.get(i);
        for (final MethodData method : methods.get(key.getQualifiedSourceName())) {
            if (method.isProperty()) {
                printPropertyAccess(logger, out, method, builder, seen);
            } else {
                printValueAccess(logger, out, method, builder, seen);
            }
        }
    }
    final String inject = out.addImport(X_Inject.class);
    for (Class<? extends ShadowDomPlugin> pluginClass : component.plugins()) {
        String plugin = out.addImport(pluginClass);
        out.println("builder.addShadowDomPlugin(").indent().print(inject).print(isSingleton(pluginClass) ? ".instance" : ".singleton").println("(" + plugin + ".class)").outdent().println(");");
    }
    ShadowDom[] shadowDoms = component.shadowDom();
    if (shadowDoms.length > 0) {
        for (ShadowDom shadowDom : shadowDoms) {
            // Calculate if we need to do any css injection.
            SourceTransform shadowStyle = null;
            if (shadowDom.styles().length > 0 || styles.isNotEmpty()) {
                final Fifo<ShadowDomStyle> localStyles = new SimpleFifo<>();
                localStyles.giveAll(shadowDom.styles());
                shadowStyle = getStyleInjectorGenerator().generateShadowStyles(logger, styles, localStyles, context);
            }
            for (String template : shadowDom.value()) {
                ContainerMetadata metadata = createMetadata();
                if (shadowStyle != null) {
                    metadata.addModifier(shadowStyle);
                }
                metadata.setSourceBuilder(sourceBuilder);
                template = resolveTemplate(logger, template, context, type, metadata);
                out.print("builder.addShadowRoot(\"").print(Generator.escape(template)).print("\"").println().println(", shadow -> {").indent();
                metadata.applyModifiers(out, "shadow");
                out.println("return shadow;").outdent().println(// just close out the shadowroot call
                "});");
            }
        }
    }
    out.print("ctor = " + support + ".register(").print("\"" + component.tagName() + "\"").println(", builder.build());").outdent().println("}").createMethod("public " + simpleName(type) + " newComponent()").returnValue("ctor.get()");
    // Print the querySelector method.
    final MethodBuffer querySelector = out.createMethod("public String querySelector()");
    if (component.extendProto().length > 1) {
        // We are extending an existing method.
        querySelector.returnValue("\"" + component.extendProto()[1] + "[is=" + component.tagName() + "]\"");
    } else {
        querySelector.returnValue("\"" + component.tagName() + "\"");
    }
    final String src = sourceBuilder.toString();
    logger.log(logLevel(typeName), "\nWeb Component Factory: \n" + src);
    pw.println(src);
    context.commit(logger, pw);
    return new RebindResult(RebindMode.USE_ALL_NEW, qualifiedName);
}