I have a class library written in Java and want to convert it to Javascript. All methods are pretty simple and mostly have to do with manipulating collections. I have this one class, GameControl, which I could instantiate and I want its methods exposed to other Javascript code on the page.
I thought to use GWT. I have a running project in GWT which compiles, but I can't figure out how to expose my instance (+functionality) of the GameControl class.
I thought using JSNI to expose my object should work, but it didn't. This is the short version of how it look like right now:
GameEntryPoint.java
import com.google.gwt.core.client.EntryPoint;
public class GameEntryPoint implements EntryPoint {
private GameControl _gameControl;
#Override
public void onModuleLoad() {
_gameControl = new GameControl();
expose();
}
public native void expose()/*-{
$wnd.game = this.#game.client.GameEntryPoint::_gameControl;
}-*/;
}
GameControl.java
package game.client;
public class GameControl {
public boolean isEmpty(int id){
// does stuff...
return true;
}
}
So, GWT indeed compiles the code, and I see that there is a GameControl_0 object being built and set into $wnd.game, but no isEmpty() method to be found.
My expected end result is to have a window.game as an instance of GameControl with all public methods GameControl exposes.
How can I do this?
Edit
As per #jusio's reply, using JSNI to expose window properties explicitly worked, but it was too verbose. I'm trying the gwt-exporter solution. Now I have
GameEntryPoint.java
package game.client;
import org.timepedia.exporter.client.ExporterUtil;
import com.google.gwt.core.client.EntryPoint;
public class GameEntryPoint implements EntryPoint {
#Override
public void onModuleLoad() {
ExporterUtil.exportAll();
}
}
RoadServer.java
package game.client;
import org.timepedia.exporter.client.Export;
import org.timepedia.exporter.client.ExportPackage;
import org.timepedia.exporter.client.Exportable;
#ExportPackage("game")
#Export("RoadServer")
public class RoadServer implements Exportable {
int _index;
int _id;
public RoadServer(int index,int id){
this._id=id;
this._index=index;
}
}
but still none of the code is exported (specifically not RoadServer).
You have exposed only instance of the GameControl. If you want to expose other methods, you'll have to expose them as well.
For example:
public native void expose()/*-{
var control = this.#game.client.GameEntryPoint::_gameControl;
var gameInstance = {
gameControl: control,
isEmpty:function(param){
control.#game.client.GameEntryPoint::isEmpty(*)(param);
}
}
$wnd.game = gameInstance;
}-*/;
Also there is a framework called gwt-exporter, it might make things easier for you
This may help.
http://code.google.com/p/gwtchismes/wiki/Tutorial_ExportingGwtLibrariesToJavascript_en
Related
Actually, I have existing SDKs and I wanted to use that SDK in the react native app.
For android
I tried adding the jar file into the libs folder of /android/app/
Added dependencies into file /android/app/build.gradle
implementation fileTree(include: ['*.jar'], dir: 'libs')
But I did not get how can I use these jar files in my js file. How can I create the object and call the methods?
The main concern is how can I use the external java libraries in my react native app?
You should use native modules them are bridge between JS and native
https://reactnative.dev/docs/native-modules-android
Example
public class DummyModule extends ReactContextBaseJavaModule {
MyDummyClass dummy // this context
public DummyModule(final ReactApplicationContext reactContext){
super(reactContext);
}
#Override
// getName is required to define the name of the module represented in
// JavaScript
public String getName() {
return "DummyModule";
}
#ReactMethod
public void startMyClass() {
this.dummy = new MyDummyClass();
}
#ReactMethod
public void fooActionClass() {
if(this.dummy != null){
this.dummy.fooAction();
}
}
}
In your javascript code
import { NativeModules } from 'react-native';
const dummyModule = NativeModules.DummyModule;
dummyModule.startMyClass();
// Make sure that u call the action when the class is instanciated.
dummyModule.fooActionClass();
Usefull question as well Sending hashmao from java to react native
I am trying to migrate from using compiler flag -XjsInteropMode JS but I run into a problem.
I have an interface called Module that looks like this:
#JsType
public interface Module {
#JsProperty
String getBasename();
}
Then I have another interface called AuthenticationModule which looks like this:
#JsType
public interface AuthenticationModule extends Module {
static final String MODULE_NAME = "authentication";
void logIn(String username, String password, JsConsumer<JavaScriptObject> onSuccess, JsConsumer<JavaScriptObject> onError);
void logOut(JsConsumer<JavaScriptObject> onSuccess, JsConsumer<JavaScriptObject> onError);
}
The module interface is just a marker interface, so when I was loading some module, I was able to cast it in the end to a module I wanted, example here:
#Override
public void getAuthenticationModule(
OnModuleLoaded<AuthenticationModule> onModuleLoaded) {
initializeIfNecessary();
JsArrayString requiredModules = JavaScriptObject.createArray().cast();
requiredModules.push(AuthenticationModule.MODULE_NAME);
modules.require(requiredModules, loadedModule -> {
onModuleLoaded.moduleLoaded((AuthenticationModule) loadedModule); // this line (the casting) throws ClassCastException
});
}
modules in this code is another interface which looks like this:
#JsType
public interface Modules {
#JsFunction
#FunctionalInterface
interface CallbackRequire {
void apply(Module module);
}
#JsProperty
String getBase();
#JsProperty
void setBase(String base);
void require(JsArrayString modules, CallbackRequire onload);
}
I followed the rules on how to migrate in this document:
https://docs.google.com/document/d/10fmlEYIHcyead_4R1S5wKGs1t2I7Fnp_PaNaa7XTEk0/edit#
I was not able to solve this issue. The best I could get was changing #JsType to #JsType(isNative = true). Then the casting was working, but another error occured, can't remember now, but I'm not sure if the isNative is really the right way to solve this issue.
After adding "(isNative = true)" to most of the interfaces, it all works again. The only thing I had to change were the MODULE_NAME fields, since they cannot be initialized in a native JsType.
I am having a JsInterop issue, while wrapping up some javascript code.
the JavaScript is something like
com = { gwidgets: {} };
com.gwidgets.Spring = function () {
this.name = "hello";
};
com.gwidgets.Spring.prototype.getName = function () {return "test";
};
The JsInterop class is:
package com.gwidgets.leaflet;
import jsinterop.annotations.JsMethod;
import jsinterop.annotations.JsType;
#JsType(isNative=true)
public class Spring {
#JsMethod
public native String getName();
}
However, when I instantiate the class and try to call the getName() method, I get an error:
leafletwrapper-0.js:1183 Uncaught TypeError: spring.getName is not a
function
Any ideas what is wrong with my code?
According to javascript you have, one solution could be to add namespace to annotation
import jsinterop.annotations.JsMethod;
import jsinterop.annotations.JsType;
#JsType(isNative=true, namespace = "com.gwidgets")
public class Spring {
#JsMethod
public native String getName();
}
Or move java class Spring to package com.gwidgets (same as javascript)
Or change namespace of javascript to match package in class Spring
VideoPlayerView is a custom native component made in Android and IOS for my particular project.
Here is a part of code exporting native module named VideoPlayerView made by ReactVideoManager.java
public class ReactVideoManager extends SimpleViewManager<MeasureChangedVideoView> {
public static final String REACT_CLASS = "VideoPlayerView";
private ThemedReactContext mReactContext;
#Override
public String getName() {
return REACT_CLASS;
}
#Override
protected MeasureChangedVideoView createViewInstance(ThemedReactContext reactContext) {
mReactContext = reactContext;
return new MeasureChangedVideoView(reactContext);
}
#ReactProp(name = "url")
public void setUrl(MeasureChangedVideoView view, #Nullable String url) {
Uri uri = Uri.parse(url);
view.setVideoURI(uri);
view.setMediaController(new MediaController(mReactContext));
view.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
}
}
Below is the error log found for the module:
Error: `VideoPlayer` has no propType for native prop `VideoPlayerView.scaleY` of native type `number`
The corresponding js component for this native view is VideoPlayer.js:
var React = require('react-native');
var { requireNativeComponent } = React;
class VideoPlayer extends React.Component {
render() {
return <VideoPlayerView {...this.props} />;
}
}
VideoPlayer.propTypes = {
url: React.PropTypes.string
};
var VideoPlayerView = requireNativeComponent('VideoPlayerView', VideoPlayer);
module.exports = VideoPlayer;
The very same module used to work in a different project B. The only difference found was presence of a react.gradle file in project B.
There is absolutely no clue where react.gradle file is generated. Also I tried restarting packager, cleaning the project building again.
The gradle dependency used in project is
compile "com.facebook.react:react-native:0.14.+"
One should definitely use the latest version and the way specified in docs https://facebook.github.io/react-native/docs/native-components-android.html#content should work fine.
So It turns out that I was using React version 0.13+ (in package.json) and the way of adding properties using #Reactprop annotation was introduced in gradle 0.14 dependency and this way doesn't quite work well with the older version of React-native(0.13).
If due to some reason you happen to work on 0.13 or pre, the way of mixing in of props manually as specified in https://github.com/facebook/react-native/issues/3478 must be followed.
I am tasked to compile the gwt project(which doesnot include HTML CSS) into JS files and add the same to an external JS/HTML file( which is in different project).
here is the java code which has to be compiled:
1. Client class:
package com.dell.supportassist.gwt.collectionReport.client;
import org.timepedia.exporter.client.Export;
import org.timepedia.exporter.client.Exportable;
#Export("HelloWorld")
public class HelloWorld implements Exportable {
public String sayHello(){
return "Hello";
}
}
EntryPoint Class:
package com.dell.supportassist.gwt.collectionReport.client;
import org.timepedia.exporter.client.Export;
import org.timepedia.exporter.client.Exportable;
#Export("HelloWorld")
public class HelloWorld implements Exportable {
public String sayHello(){
return "Hello";
}
}
My issue is, once the above gwt project/classes are complied, i want to access 'sayHello()' method in ma external javascript like this:
var person = hello.sayHello();
system.log(person);
But this is throwing a run time error saying 'hello' is not defined.
P.S I am trying to use the GWT compiled JS in an external HTML, JS Present in Durandaljs Framework.
Haven't done this kind of stuff for quite some time but you could achieve this using JSNI, which allows you to write native JS in GWT. From JSNI you can reference your GWT methods. That way you could define a function (on window, most typically) which would then become available to regular JS. From this JSNI-method you can reference your GWT/Java code.
Code example:
public class MyModule implements EntryPoint {
static {
export();
}
/**
* Makes our setData method accessible from plain JS
*/
private static native void export() /*-{
$wnd.setData = #my.package.MyModule::setData(Lcom/google/gwt/core/client/JavaScriptObject;);
}-*/;
private static void setData(JavaScriptObject javaScriptObject) {
// this method is now reachable as window.setData
}
}