下面列出了怎么用com.google.gwt.core.client.JavaScriptObject的API类实例代码及写法,或者点击链接到github查看源代码。
@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));
}
@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;
}
}
/**
* 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]);
}
}
}-*/;
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;
}-*/;
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);
}
}
/**
* <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() );
}
@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);
}
@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;
}
/**
* 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);
}
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());
}
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;
}
};
}-*/;
@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);
}
});
}
@Override
public Object parseJsonObject(String json) {
if (json != null)
return JsonUtils.<JavaScriptObject> safeEval(json);
return null;
}
/**
* 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);
}
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() );
}
/**
* 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);
}
}
@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) {}
}
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);
}-*/;
native JavaScriptObject getIconPreferredSize()/*-{
var marker = [email protected]kMapFeatureBase::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.
}-*/;
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);
}
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>();
}
}
public static native double distanceBetweenPoints(JavaScriptObject map, MockMap.LatLng point1, MockMap.LatLng point2)/*-{
var pt1 = [[email protected]ockMap.LatLng::latitude,
[email protected]ockMap.LatLng::longitude],
pt2 = [[email protected]ockMap.LatLng::latitude,
[email protected]ockMap.LatLng::longitude];
return map.distance(pt1, pt2);
}-*/;
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);
}
}-*/;
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);
}
}-*/;
/**
* 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');
}
}-*/;
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);
}
}
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;
}-*/;
/**
* 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
[email protected]gAndDropUploader::callUploadedFolder(*)(callback, path, JSON.parse(xhr.response).error)
} else {
// Folder created
[email protected]gAndDropUploader::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;
}-*/;
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$/, "");
}-*/;
@Override
public JavaScriptObject toJavaScript() {
return config;
}