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

The following examples show how to use com.google.gwt.core.client.JavaScriptObject. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SViewBuilderJs.java    From swellrt with Apache License 2.0 6 votes vote down vote up
@Override
public void visit(SList<T> list) {

  JavaScriptObject jsarray = JsoView.createArray();

  for (int i = 0; i < list.size(); i++) {
    try {
      list.pick(i).accept(this);
      jsArrayPush(jsarray, currentObject);
    } catch (SException e) {
      ex = e;
      return;
    }
  }

  currentObject = jsarray;

}
 
Example #2
Source File: TurboOverlaySerdes.java    From requestor with Apache License 2.0 6 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public <C extends Collection<JavaScriptObject>> C deserialize(Class<C> collectionType, String response,
                                                              DeserializationContext context) {
    JsArray<JavaScriptObject> jsArray = eval(response);
    if (collectionType.equals(List.class) || collectionType.equals(Collection.class)
            || collectionType.equals(JsArrayList.class)) {
        return (C) new JsArrayList(jsArray);
    } else {
        C col = context.getInstance(collectionType);
        for (int i = 0; i < jsArray.length(); i++) {
            JavaScriptObject t = jsArray.get(i);
            col.add(t);
        }
        return col;
    }
}
 
Example #3
Source File: FormDataSerializerNative.java    From requestor with Apache License 2.0 6 votes vote down vote up
@Override
public Payload serialize(FormData formData) {
    if (formData.getFormElement() != null)
        return new Payload(FormDataOverlay.create(formData.getFormElement()));

    FormDataOverlay overlay = FormDataOverlay.create();
    for (FormData.Param param : formData) {
        final Object value = param.getValue();
        if (value instanceof String) {
            overlay.append(param.getName(), (String) value);
        } else {
            overlay.append(param.getName(), (JavaScriptObject) value, param.getFileName());
        }
    }
    return new Payload(overlay);
}
 
Example #4
Source File: StateMap.java    From incubator-retired-wave with Apache License 2.0 6 votes vote down vote up
/**
 * Copy key-value pairs from jsonObject; accept only string, number, or
 * null values; skip all pairs with other values. This step makes sure that
 * the StateMap only contains sanitized keys prefixed with ':'. Note that
 * hasOwnProperty() cannot be used on jsonObject. However, typeof and null
 * comparison are safe.
 *
 * @param source JavaScriptObject to copy from.
 * @param target JavaScriptObject to copy into.
 */
public final static native void copyJson(JavaScriptObject source, JavaScriptObject target) /*-{
  for (var key in target) {
    if (target.hasOwnProperty(key)) {
      delete target[key];
    }
  }

  for (var key in source) {
    if (source[key] === null) {
      target[':' + key] = null;
    } else if (typeof source[key] === 'string') {
      target[':' + key] = source[key];
    } else if (typeof source[key] === 'number') {
      target[':' + key] = String(source[key]);
    }
  }
}-*/;
 
Example #5
Source File: JacksonTypeOracle.java    From gwt-jackson with Apache License 2.0 6 votes vote down vote up
/**
 * <p>Constructor for JacksonTypeOracle.</p>
 *
 * @param logger a {@link com.google.gwt.core.ext.TreeLogger} object.
 * @param typeOracle a {@link com.google.gwt.core.ext.typeinfo.TypeOracle} object.
 */
public JacksonTypeOracle( TreeLogger logger, TypeOracle typeOracle ) {
    this.logger = logger;
    this.typeOracle = typeOracle;

    this.objectReaderType = typeOracle.findType( ObjectReader.class.getCanonicalName() );
    this.objectWriterType = typeOracle.findType( ObjectWriter.class.getCanonicalName() );
    this.keySerializerType = typeOracle.findType( KeySerializer.class.getCanonicalName() );
    this.keyDeserializerType = typeOracle.findType( KeyDeserializer.class.getCanonicalName() );
    this.jsonSerializerType = typeOracle.findType( JsonSerializer.class.getCanonicalName() );
    this.jsonDeserializerType = typeOracle.findType( JsonDeserializer.class.getCanonicalName() );
    this.mapType = typeOracle.findType( Map.class.getCanonicalName() );
    this.iterableType = typeOracle.findType( Iterable.class.getCanonicalName() );
    this.jsoType = typeOracle.findType( JavaScriptObject.class.getCanonicalName() );
    this.enumType = typeOracle.findType( Enum.class.getCanonicalName() );
    this.stringType = typeOracle.findType( String.class.getCanonicalName() );
}
 
Example #6
Source File: JSMolecule.java    From openchemlib-js with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public native String toSVG(int width, int height, String id, JavaScriptObject options)
/*-{
	//todo: re-enable this check once it becomes possible to change the font
	//if (!$doc.createElement) {
	//	throw new Error('Molecule#toSVG cannot be used outside of a browser\'s Window environment');
	//}
	options = options || {};
	var factorTextSize = options.factorTextSize || 1;
  var autoCrop = options.autoCrop === true;
  var autoCropMargin = typeof options.autoCropMargin === 'undefined' ? 5 : options.autoCropMargin;
	var svg =  [email protected]::getSVG(IIFZILjava/lang/String;Lcom/google/gwt/core/client/JavaScriptObject;)(width, height, factorTextSize, autoCrop, autoCropMargin, id, options);
	if (options.fontWeight) {
    svg = svg.replace(/font-family=" Helvetica" /g, 'font-family=" Helvetica" font-weight="' + options.fontWeight + '" ');
  }
  if (options.strokeWidth) {
   svg = svg.replace(/stroke-width="[^"]+"/g, 'stroke-width="' + options.strokeWidth + '"');
  }
  return svg;
}-*/;
 
Example #7
Source File: OverlaySerdesTest.java    From requestor with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public void testDeserializeCollection() throws Exception {
    DeserializationContext ctx = new DeserializationContext(JavaScriptObject.class) {
        @Override
        public <T> T getInstance(Class<T> type) {
            return (T) new ArrayList<Object>();
        }
    };

    String input = "[{\"name\":\"John Doe\",\"age\":31},{\"name\":\"Alice\",\"age\":27}]";

    JsArray<JavaScriptObject> expected = (JsArray<JavaScriptObject>) JavaScriptObject.createArray();
    expected.push(create("John Doe", 31));
    expected.push(create("Alice", 27));

    List<JavaScriptObject> output = serdes.deserialize(List.class, input, ctx);
    JsArray<JavaScriptObject> outputArray = (JsArray<JavaScriptObject>) JavaScriptObject.createArray();
    outputArray.push(output.get(0));
    outputArray.push(output.get(1));

    assertEquals(JsonSerdes.stringify(expected), JsonSerdes.stringify(outputArray));
}
 
Example #8
Source File: SimpleDemo.java    From jts with GNU Lesser General Public License v2.1 6 votes vote down vote up
private void showPoland() {
	WKTReader r = new WKTReader();
	try {
		Geometry g = r.read(s);
		g.setSRID(4326);

		Geometry g2 = g.buffer(1);
		Geometry g3 = g2.difference(g);

		JavaScriptObject f1 = parseWKT(g.toString());
		JavaScriptObject f2 = parseWKT(g3.toString());
		JsArray<JavaScriptObject> fs = JsArray.createArray().cast();
		fs.push(f1);
		fs.push(f2);

		addFeatures(mMap, fs);
	} catch (ParseException e) {
		sLogger.log(Level.WARNING, "Unable to parse wkb", e);
	}
}
 
Example #9
Source File: BarChart.java    From dashbuilder with Apache License 2.0 5 votes vote down vote up
private native void drawBar(JavaScriptObject data)/*-{
       canvas = [email protected]::getNativeElement()();
       nativeCanvas = [email protected]::getNativeCanvas()();
       if(nativeCanvas != null) {
           nativeCanvas.destroy();
       }

       var options = [email protected]::constructOptions()();
       nativeCanvas = new $wnd.Chart(canvas.getContext("2d")).Bar(data, options);
       [email protected]::setNativeCanvas(Lcom/google/gwt/core/client/JavaScriptObject;)(nativeCanvas);
}-*/;
 
Example #10
Source File: MockMapFeatureBase.java    From appinventor-extensions with Apache License 2.0 5 votes vote down vote up
public static native double distanceBetweenPoints(JavaScriptObject map, MockMap.LatLng point1, MockMap.LatLng point2)/*-{
  var pt1 = [point1.@com.google.appinventor.client.editor.simple.components.MockMap.LatLng::latitude,
        point1.@com.google.appinventor.client.editor.simple.components.MockMap.LatLng::longitude],
      pt2 = [point2.@com.google.appinventor.client.editor.simple.components.MockMap.LatLng::latitude,
        point2.@com.google.appinventor.client.editor.simple.components.MockMap.LatLng::longitude];
  return map.distance(pt1, pt2);
}-*/;
 
Example #11
Source File: GwtMockitoTest.java    From gwtmockito with Apache License 2.0 5 votes vote down vote up
@Test
@SuppressWarnings("unused")
public void shouldAllowOnlyJavascriptCastsThatAreValidJavaCasts() {
  // Casts to ancestors should be legal
  JavaScriptObject o = Document.get().createDivElement().cast();
  Node n = Document.get().createDivElement().cast();
  DivElement d = Document.get().createDivElement().cast();

  // Casts to sibling elements shouldn't be legal (even though they are in javascript)
  try {
    IFrameElement i = Document.get().createDivElement().cast();
    fail("Exception not thrown");
  } catch (ClassCastException expected) {}
}
 
Example #12
Source File: Controller.java    From incubator-retired-wave with Apache License 2.0 5 votes vote down vote up
/**
 * Generic constructor that can be used for testing.
 *
 * @param library the gadget RPC library object.
 */
// @VisibleForTesting
protected Controller(JavaScriptObject library) {
  setGadgetRpcLibrary(library);
  for (Service service : Service.values()) {
    registerService(service.getName());
    serviceMap.put(service.getName(), service);
  }
}
 
Example #13
Source File: AbstractJsonWriterTest.java    From gwt-jackson with Apache License 2.0 5 votes vote down vote up
public void testRootJavaScriptObject() {
    Person person = JavaScriptObject.createObject().cast();
    person.setFirstName( "Bob" );
    person.setLastName( "Morane" );

    JsonWriter jsonWriter = newJsonWriter();
    jsonWriter.setLenient( true );

    jsonWriter.value( person );
    jsonWriter.close();

    assertEquals( "{\"firstName\":\"Bob\",\"lastName\":\"Morane\"}", jsonWriter.getOutput() );
}
 
Example #14
Source File: AutomationEditor.java    From document-management-software with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void onDraw() {
	if (title != null) {
		Label label = new Label(I18N.message(title));
		label.setHeight(20);
		addMember(label);
	}
	addMember(editor);

	editor.startEditor();
	editor.setMode(AceEditorMode.VELOCITY);
	editor.setTheme(AceEditorTheme.ECLIPSE);
	editor.setShowGutter(true);
	editor.setShowPrintMargin(false);
	editor.setAutocompleteEnabled(true);

	AceEditor.addCompletionProvider(new AutomationCompletionProvider());

	editor.setWidth(getWidth() - 20 + "px");
	editor.setHeight(getHeight() - 20 + "px");

	if (text != null)
		editor.setText(text);

	editor.addOnChangeHandler(new AceEditorCallback() {

		@Override
		public void invokeAceCallback(JavaScriptObject obj) {
			if (changedHandler != null)
				changedHandler.onChanged(null);
		}
	});
}
 
Example #15
Source File: InputFile.java    From putnami-web-toolkit with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void uploadData(JavaScriptObject object) {
	StyleUtils.removeStyle(this, STYLE_ERROR);
	this.fileId = UUID.uuid();
	this.initProgressBar();
	nativeUploadData(object, this, urlUpload + this.fileId,
		CsrfController.get().getHeader(), CsrfController.get().getToken());
}
 
Example #16
Source File: PlaygroundView.java    From caja with Apache License 2.0 5 votes vote down vote up
private native JavaScriptObject makeUriPolicy() /*-{
      return {
        mitigate: function (uri) {
          // Skip rewriting jquery and jqueryui when loaded
          // from the google cdn
          if (uri.getDomain() === "ajax.googleapis.com" &&
              (uri.getPath().indexOf("/ajax/libs/jquery/") === 0 ||
               uri.getPath().indexOf("/ajax/libs/jqueryui/") === 0))  {
            return uri;
          }
          return null;
        },
        fetch: $wnd.caja.policy.net.ALL.fetch,
        rewrite: function (uri, uriEffect, loaderType, hints) {
          if (uriEffect === $wnd.html4.ueffects.NEW_DOCUMENT) {
            return uri;
          }
          if (uriEffect === $wnd.html4.ueffects.SAME_DOCUMENT &&
               (loaderType === $wnd.html4.ltypes.SANDBOXED ||
                 loaderType === $wnd.html4.ltypes.DATA)) {
            if (hints && hints.XHR) {
              return uri;
            }
            return "http://www.gmodules.com/gadgets/proxy"
                + "?url=" + encodeURIComponent(uri.toString())
                + "&container=caja";
          }
          return null;
        }
      };
}-*/;
 
Example #17
Source File: WebModelFactory.java    From swellrt with Apache License 2.0 5 votes vote down vote up
@Override
public Object parseJsonObject(String json) {
  if (json != null)
    return JsonUtils.<JavaScriptObject> safeEval(json);

  return null;
}
 
Example #18
Source File: TemplateNodeMutationHandler.java    From swellrt with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a renderer for &lt;template&gt; 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 #19
Source File: MockMarker.java    From appinventor-extensions with Apache License 2.0 5 votes vote down vote up
native JavaScriptObject getIconPreferredSize()/*-{
  var marker = this.@com.google.appinventor.client.editor.simple.components.MockMapFeatureBase::feature;
  if (marker) {
    var img = marker._icon && marker._icon.querySelector('svg');
    if (img) {
      return [parseInt(img.getAttribute('width')), parseInt(img.getAttribute('height'))];
    }
    img = marker._icon && marker._icon.querySelector('img');
    if (img) {
      return [img.naturalWidth, img.naturalHeight];
    }
  }
  return [-1, -1];  // this is only called for when the width/height is -1, so this is idempotent.
}-*/;
 
Example #20
Source File: TurboOverlaySerdesTest.java    From requestor with Apache License 2.0 5 votes vote down vote up
public void testSerializeCollection() throws Exception {
    JsArrayList<JavaScriptObject> input = new JsArrayList<JavaScriptObject>(create("John Doe", 31),
            create("Alice", 27));
    String expected = "[{\"name\":\"John Doe\",\"age\":31},{\"name\":\"Alice\",\"age\":27}]";

    String output = serdes.serialize(input, null);

    assertEquals(expected, output);
}
 
Example #21
Source File: FullCalendar.java    From gwtbootstrap3-extras with Apache License 2.0 5 votes vote down vote up
public FullCalendar(final String id, final ViewOption defaultView, final CalendarConfig config, final boolean editable) {
    getElement().setId(id);
    this.currentView = defaultView == null ? ViewOption.month : defaultView;
    this.config = config;
    this.editable = editable;
    loaded = false;
    if (languageScripts == null) {
        languageScripts = new HashMap<String, JavaScriptObject>();
    }
}
 
Example #22
Source File: ControllerGwtTest.java    From swellrt with Apache License 2.0 5 votes vote down vote up
/**
 * Issues a simulated gadget RPC call at JS level.
 *
 * @param gadgetId ID of the gadget that would generate this call.
 * @param service name of the service.
 * @param args call arguments.
 */
public void simulateCallFromGadget(String gadgetId, String service,
                                   JavaScriptObject ... args) {
  JsArrayMixed arr = JsArrayMixed.create();
  for (int i = 0; i < args.length; ++i) {
    arr.put(i, args[i]);
  }
  simulateCallFromGadgetHelper(gadgetId, service, arr);
}
 
Example #23
Source File: VComboBoxMultiselect.java    From vaadin-combobox-multiselect with Apache License 2.0 5 votes vote down vote up
public native void attachMousewheelListenerNative(Element element, JavaScriptObject mousewheelListenerFunction)
/*-{
    if (element.addEventListener) {
        // FireFox likes "wheel", while others use "mousewheel"
        var eventName = 'onmousewheel' in element ? 'mousewheel' : 'wheel';
        element.addEventListener(eventName, mousewheelListenerFunction);
    }
}-*/;
 
Example #24
Source File: VComboBoxMultiselect.java    From vaadin-combobox-multiselect with Apache License 2.0 5 votes vote down vote up
public native void detachMousewheelListenerNative(Element element, JavaScriptObject mousewheelListenerFunction)
/*-{
    if (element.addEventListener) {
        // FireFox likes "wheel", while others use "mousewheel"
        var eventName = element.onwheel===undefined?"mousewheel":"wheel";
        element.removeEventListener(eventName, mousewheelListenerFunction);
    }
}-*/;
 
Example #25
Source File: GadgetWidget.java    From swellrt with Apache License 2.0 5 votes vote down vote up
/**
 * Utility function to send Gadget mode to Wave gadget.
 *
 * @param target the gadget frame ID.
 * @param mode JSON string of Gadget state.
 */
public native void sendModeRpc(String target, JavaScriptObject mode) /*-{
  try {
    $wnd.gadgets.rpc.call(target, 'wave_gadget_mode', null, mode);
  } catch (e) {
    // HACK(user): Ignoring any failure for now.
    @org.waveprotocol.wave.client.gadget.GadgetLog::log(Ljava/lang/String;)
    ('wave_gadget_mode RPC failed');
  }
}-*/;
 
Example #26
Source File: SliderBase.java    From gwtbootstrap3-extras with Apache License 2.0 5 votes vote down vote up
private void updateSliderForStringArray(SliderOption option, List<String> value) {
    JsArrayString array = JavaScriptObject.createArray().cast();
    for (String val : value) {
        array.push(val);
    }
    if (isAttached()) {
        setAttribute(getElement(), option.getName(), array);
        refresh();
    } else {
        String arrayStr = JsonUtils.stringify(array);
        attributeMixin.setAttribute(option.getDataAttribute(), arrayStr);
    }
}
 
Example #27
Source File: PlaygroundEditor.java    From caja with Apache License 2.0 5 votes vote down vote up
public native JavaScriptObject initialize(Element el) /*-{
  el.focus();
  var jsEditor = $wnd.CodeMirror.fromTextArea(el, {
    parserfile: ["parsecss.js", "tokenizejavascript.js",
      "parsejavascript.js", "parsexml.js", "parsehtmlmixed.js" ],
    stylesheet: ["css/xmlcolors.css","css/jscolors.css","css/csscolors.css"],
    autoMatchParens : true,
    path : 'js/',
    height : '100%',
    textWrapping: false,
    lineNumbers: true,
    breakPoints: true,
  });
  return jsEditor;
}-*/;
 
Example #28
Source File: DragAndDropUploader.java    From document-management-system with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Upload folder. This is a Javascript native function.
 */
public native JavaScriptObject createFolder(JavaScriptObject file, String filePostName, String path, AsyncCallback<UploaderEvent> callback, String context) /*-{
     var self = this;
     var xhr = new XMLHttpRequest();
     var url = context + '/frontend/CreateFolder';

     xhr.open('POST', url, true);

     xhr.onreadystatechange = function (aEvt) {
       if (xhr.readyState == 4) {
         if ("" !== xhr.response && "" !== JSON.parse(xhr.response).error) {
           // Error
           self.@com.openkm.frontend.client.widget.filebrowser.uploader.DragAndDropUploader::callUploadedFolder(*)(callback, path, JSON.parse(xhr.response).error)
         } else {
           // Folder created
           self.@com.openkm.frontend.client.widget.filebrowser.uploader.DragAndDropUploader::callUploadedFolder(*)(callback, path, null)
         }
       }
     };

     var formData = new FormData();
     formData.append(filePostName, file);
     formData.append('path', path);

     // Kick off the multipart/form-data upload
     xhr.send(formData);

     return xhr;
   }-*/;
 
Example #29
Source File: JSONUtil.java    From core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static native String pretty(JavaScriptObject obj, String indent)/*-{

        var result = "";
        if (indent == null) indent = "";

        for (var property in obj)
        {
            var value = obj[property];
            if (typeof value == 'string')
                value = "'" + value + "'";
            else if (typeof value == 'object')
            {
                if (value instanceof Array)
                {
                    // Just let JS convert the Array to a string!
                    value = "[ " + value + " ]";
                }
                else
                {
                    // Recursive dump
                    // (replace "  " by "\t" or something else if you prefer)
                    var od = @org.jboss.as.console.client.shared.JSONUtil::pretty(Lcom/google/gwt/core/client/JavaScriptObject;Ljava/lang/String;)(value, indent + "\t");
                    // If you like { on the same line as the key
                    //value = "{\n" + od + "\n" + indent + "}";
                    // If you prefer { and } to be aligned
                    value = "\n" + indent + "{\n" + od + "\n" + indent + "}";
                }
            }
            result += indent + "'" + property + "' : " + value + ",\n";
        }
        return result.replace(/,\n$/, "");

    }-*/;
 
Example #30
Source File: JsContact.java    From actor-platform with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public JavaScriptObject buildOverlay(Contact prev, Contact current, Contact next) {
    return null;
}