I'm trying to add spans when constructor of some class called. I'm using opentelemetry javaagent and extensions to add tracing to my application.
import io.opentelemetry.api.GlobalOpenTelemetry;
import io.opentelemetry.api.trace.Span;
import io.opentelemetry.api.trace.Tracer;
import io.opentelemetry.javaagent.extension.instrumentation.TypeInstrumentation;
import io.opentelemetry.javaagent.extension.instrumentation.TypeTransformer;
import net.bytebuddy.asm.Advice;
import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.matcher.ElementMatcher;
import net.bytebuddy.matcher.ElementMatchers;
import static net.bytebuddy.matcher.ElementMatchers.isConstructor;
import static net.bytebuddy.matcher.ElementMatchers.named;
public class ClassConstructorInstrumentation implements TypeInstrumentation {
#Override
public ElementMatcher<TypeDescription> typeMatcher() {
return ElementMatchers
.namedOneOf("org.example.ServiceManagerDummy");
}
#Override
public void transform(TypeTransformer transformer) {
transformer.applyAdviceToMethod(
isConstructor(),
this.getClass().getName() + "$ConstructorSpanCreateAdvice");
// transformer.applyAdviceToMethod(
// named("dummyMethod"),
// this.getClass().getName() + "$ConstructorSpanCreateAdvice");
}
#SuppressWarnings("unused")
public static class ConstructorSpanCreateAdvice {
#Advice.OnMethodEnter
public static void onEnter() {
System.out.println("START SPAN ");
}
#Advice.OnMethodExit(onThrowable = Throwable.class)
public static void onExit(
#Advice.Thrown Throwable throwable
) {
System.out.println("END SPAN ");
}
}
}
public class ServiceManagerDummy {
public ServiceManagerDummy() {
System.out.println("SERVICE MANAGER CONSTR");
dummyMethod();
}
private void dummyMethod() {
System.out.println("DUMMY METHOD CALLED");
}
}
I'm using a simple configuration as above just to verify that when the constructor was called my advice method log it. But when it configured to add some logs when the constructor was called, I received nothing in the log. But when I add config for method calling (commented code) it works. What's wrong in my configuration?
What Byte Buddy would normally do would be to wrap the constructor in a try-finally-block. For a constructor, that is not possible as the super method call cannot be wrapped in such a block. "onThrowable" is therefore not possible for constructors.
I m trying to use native modules on react native to get the device name and package installer from android , but I got always a null value ?
my code like the following
the result always is null !
// DeviceInfoModule.java
package com.example;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.ReactMethod;
import android.annotation.SuppressLint;
import android.os.Build;
import android.content.Context;
import android.os.AsyncTask;
public class DeviceInfoModule extends ReactContextBaseJavaModule {
public DeviceInfoModule(ReactApplicationContext reactContext) {
super(reactContext);
}
#Override
public String getName() {
return "DeviceInfoModule";
}
#ReactMethod
public void getDeviceName(final Callback callback) {
getDeviceNameHandler(callback);
}
#ReactMethod
public void getDeviceInstaller(final Callback callback) {
getDevicePackager(callback);
}
private void getDeviceNameHandler(final Callback callback) {
#SuppressLint("StaticFieldLeak") AsyncTask<Void,Void,Void> myAsyncTask = new AsyncTask<Void,Void,Void>() {
#SuppressLint("StaticFieldLeak")
#Override
protected Void doInBackground(final Void ... params) {
String device_Name = Build.MANUFACTURER + "-" + Build.MODEL;
callback.invoke( device_Name, device_Name);
return null;
}
};
myAsyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
private void getDevicePackager(final Callback callback) {
#SuppressLint("StaticFieldLeak") AsyncTask<Void,Void,Void> myAsyncTask = new AsyncTask<Void,Void,Void>() {
#Override
protected Void doInBackground(final Void ... params) {
Context context = getReactApplicationContext();
String installer = context.getPackageManager().getInstallerPackageName(context.getPackageName());
callback.invoke(null, installer);
return null;
}
};
myAsyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
}
and packages are :
// ReactNativePackages.java
package com.example;
import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;
import com.carexs.DeviceInfoModule;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class ReactNativePackages implements ReactPackage {
#Override
public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
return Collections.emptyList();
}
#Override
public List<NativeModule> createNativeModules(
ReactApplicationContext reactContext) {
List<NativeModule> modules = new ArrayList<>();
modules.add(new DeviceInfoModule(reactContext));
return modules;
}
}
in the Main Application class I added the package
protected List<ReactPackage> getPackages() {
List<ReactPackage> packages = new PackageList(this).getPackages();
packages.add(new CxsNativeUtilsPackage());
packages.add(new ReactNativePackages());
return packages;
}
in my app I have the following code
const DeviceInfo = NativeModules.DeviceInfoModule;
DeviceInfo.getDeviceInstaller((err: string, name: string) => {
if (err) {
console.log('error', err);
} else {
console.log('device name', name);
}
});
any help? , thank you.
I found a solution and maybe someone will need it someday , I found that react native methods that I have created is not working maybe because of some depraceted modules or other issue on the code I m not sure exactly , I have changed those methods to new version , for example:
#ReactMethod
getDevicePackager() // (renamed to getDeviceInstaller()) method in DeviceInfoModule is changed to the following
// will be
#ReactMethod(isBlockingSynchronousMethod = true)
public String getInstallerPackageNameSync() {
String packageName = getReactApplicationContext().getPackageName();
String installerPackageName = getReactApplicationContext().getPackageManager().getInstallerPackageName(packageName);
if (installerPackageName == null) {
return "unknown";
}
return installerPackageName;
}
#ReactMethod
public void getDeviceInstaller(Promise p) { p.resolve(getInstallerPackageNameSync()); }
I'm starting to code my own minecraft 1.14.4 mod. I want to create a very simple mod which will just display a clok showing the in-game time (I couldn't find a similar updated mod, since all other mods show the real-time time, not the in-game time). I took the example mod which comes with Forge, and added some custom code.
When I load the mod, the player turns invisible and immobile. He is there, I can look around and dig and so on, but I can not see him nor move.
If I suppress my custom code, it works... very weird to me.
this is my code so far (it does not show anything since I am stuck in this problem).
package com.alef.simpleclock;
import net.minecraft.block.Block;
import net.minecraft.block.Blocks;
import net.minecraft.client.entity.player.ClientPlayerEntity;
import net.minecraft.world.World;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.RegistryEvent;
import net.minecraftforge.event.TickEvent;
import net.minecraftforge.event.entity.EntityJoinWorldEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.InterModComms;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.Mod.EventBusSubscriber;
import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent;
import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent;
import net.minecraftforge.fml.event.lifecycle.InterModEnqueueEvent;
import net.minecraftforge.fml.event.lifecycle.InterModProcessEvent;
import net.minecraftforge.fml.event.server.FMLServerStartingEvent;
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.util.stream.Collectors;
// The value here should match an entry in the META-INF/mods.toml file
#Mod("simpleclock")
public class SimpleClock
{
// Directly reference a log4j logger.
private static final Logger LOGGER = LogManager.getLogger();
public static boolean startTimer;
public static int tick;
public SimpleClock() {
// Register the setup method for modloading
FMLJavaModLoadingContext.get().getModEventBus().addListener(this::setup);
// Register the enqueueIMC method for modloading
FMLJavaModLoadingContext.get().getModEventBus().addListener(this::enqueueIMC);
// Register the processIMC method for modloading
FMLJavaModLoadingContext.get().getModEventBus().addListener(this::processIMC);
// Register the doClientStuff method for modloading
FMLJavaModLoadingContext.get().getModEventBus().addListener(this::doClientStuff);
// Register ourselves for server and other game events we are interested in
MinecraftForge.EVENT_BUS.register(this);
}
private void setup(final FMLCommonSetupEvent event)
{
// some preinit code
LOGGER.info("HELLO FROM PREINIT");
LOGGER.info("DIRT BLOCK >> {}", Blocks.DIRT.getRegistryName());
}
private void doClientStuff(final FMLClientSetupEvent event) {
// do something that can only be done on the client
LOGGER.info("Got game settings {}", event.getMinecraftSupplier().get().gameSettings);
}
private void enqueueIMC(final InterModEnqueueEvent event)
{
// some example code to dispatch IMC to another mod
InterModComms.sendTo("examplemod", "helloworld", () -> { LOGGER.info("Hello world from the MDK"); return "Hello world";});
}
private void processIMC(final InterModProcessEvent event)
{
// some example code to receive and process InterModComms from other mods
LOGGER.info("Got IMC {}", event.getIMCStream().
map(m->m.getMessageSupplier().get()).
collect(Collectors.toList()));
}
// You can use SubscribeEvent and let the Event Bus discover methods to call
#SubscribeEvent
public void onServerStarting(FMLServerStartingEvent event) {
// do something when the server starts
LOGGER.info("HELLO from server starting");
}
// You can use EventBusSubscriber to automatically subscribe events on the contained class (this is subscribing to the MOD
// Event bus for receiving Registry Events)
#Mod.EventBusSubscriber(bus=Mod.EventBusSubscriber.Bus.MOD)
public static class RegistryEvents {
#SubscribeEvent
public static void onBlocksRegistry(final RegistryEvent.Register<Block> blockRegistryEvent) {
// register a new block here
LOGGER.info("HELLO from Register Block");
}
}
#EventBusSubscriber
public static class showClock
{
#SubscribeEvent
public static void onJoin(final EntityJoinWorldEvent event)
{
if (event.getEntity() != null && event.getEntity() instanceof ClientPlayerEntity)
{
LOGGER.info("WELCOME " + event.getEntity().getName() + "!!!");
event.setCanceled(true);
if (!SimpleClock.startTimer)
{
SimpleClock.startTimer = true;
}
}
}
#SubscribeEvent
public static void timer(final TickEvent.WorldTickEvent event)
{
if (SimpleClock.startTimer)
{
if (SimpleClock.tick >= 1000)
{
SimpleClock.tick = 0;
drawClock(event.world);
}
else
{
SimpleClock.tick++;
}
}
}
private static void drawClock(World world)
{
int time = (int) world.getWorldInfo().getDayTime() % 1000;
LOGGER.info(time);
}
}
}
Any help is welcome!!!
I'm currently coding a project Java in eclipse which has two classes. The first class (open) I use to send a specific string to my second class (viewer) and then run my second class. The second class (viewer) I have imported into my program in the form of a jar file. I have done it this way as class viewer is a pdf viewer that i created using apache PDFBox and class open sends the file to the viewer to use, but the file will be different depending on many conditions (that are not relevant) in class open. The point is that class open needs to be separate from class viewer and can not simply be two different methods in one class. I would like to know if there is a way for class open to know when class viewer has been closed, as currently I am using a while loop, which just eats up memory and is very inefficient. The code I have does currently work, but I feel there is a better way, perhaps using listeners. This is the code for closing class viewer:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
//and import swing components ect
Public class viewer extends javax.swing.JFrame
implements KeyListener,
ActionListener{
private javax.swing.JButton zoomIn;
private javax.swing.JButton zoomOut;
//and a bunch more swing components
public static boolean closed = false;
public static String fileName = "";
public viewer()
{
}
private void initComponents() throws IOException
{
addWindowListener(new java.awt.event.WindowAdapter()
{
#Override
public void windowClosing(java.awt.event.WindowEvent evt)
{
exitApplication();
}
});
}
private void exitMenuItemActionPerformed(ActionEvent evt)
{
if( document != null )
{
try
{
document.close();
}
catch( IOException e )
{
throw new RuntimeException(e);
}
}
closed = true;
System.exit(0);
}
public static void main(String filename) throws Exception
{
fileName = filename;
viewer mainViewer = new viewer();
String[] splittedStr = fileName.split("/");
BASETITLE = splittedStr[splittedStr.length - 1];
if (fileName != null)
{
mainViewer.openPDFFile(fileName);
}
mainViewer.setVisible(true);
}
This is my code from class open:
public static void main(String[] args) throws Exception {
String fileName = "C:/Files/Test.pdf";
viewer.main(fileName);
while(viewer.closed == false)
{
if(viewer.closed == true)
{
System.out.print("The Viewer Has Been Closed");
}
}
}
I want to know when it is closed so I can delete the file on the local drive. Thanks for your help!
Either you pass a callback (e.g. a Runnable) as argument to viewer.main, like viewer.main(fileName, () -> System.out.print("The Viewer Has Been Closed")) and make sure that it is called when the process is done, or you do as you've done except that you sleep your main thread a short time in the while loop, like Thread.sleep(100).
okay so I actually found an answer to my question and I'll just post it in case someone else had the same problem as me. I added a interface to the open class with the method close as shown:
import mainpackage.viewer;
public class Open implements closeInterface{
public Open() { }
public static String fileName;
public static void main(String[] args) throws Exception {
fileName = "C:/Files/Test.pdf";
run();
}
#Override
public void close() {
System.out.print("The Viewer Has Been Closed");
}
public static void run() throws Exception
{
viewer view = new viewer();
view.main(fileName);
view.addListener(new Open());
}
}
This was my code for my interface:
package mainpackage;
public interface closeInterface {
public void close();
}
And this was the snipit of code for my Viewer class
public class viewer extends javax.swing.JFrame {
private static closeInterface Closed;
private void initComponents() throws IOException
{
addWindowListener(new java.awt.event.WindowAdapter()
{
#Override
public void windowClosing(java.awt.event.WindowEvent evt)
{
exitApplication();
}
});
}
private void exitApplication()
{
try
{
if( document != null )
{
document.close();
}
}
catch( IOException io )
{
//do nothing because we are closing the application
}
Closed.close();
this.setVisible( false );
this.dispose();
}
public void addListener(closeInterface closed){
Closed = closed;
}
}
Thanks for everyone's help!
I am working on application in Vaadin for my classes.
I have to draw some map on the screen so I'm using gwt-graphics lib.
I have also some servlet which is waiting for requests.
When some specific request will come view of the map should be changed.
It lead me to prepare custom event:
// class NewModulePositionHandler
package com.example.locator;
import com.google.gwt.event.shared.EventHandler;
public interface NewModulePositionHandler extends EventHandler {
void onNewModulePosition(NewModulePositionEvent event);
}
Below implementation of my custom event:
import com.google.gwt.event.shared.GwtEvent;
public class NewModulePositionEvent extends GwtEvent<NewModulePositionHandler> {
private static final Type<NewModulePositionHandler> TYPE = new Type<NewModulePositionHandler>();
private final String m_Color;
public NewModulePositionEvent(String color) {
m_Color = color;
}
public static Type<NewModulePositionHandler> getType() {
return TYPE;
}
public String getColor() {
return m_Color;
}
#Override
public com.google.gwt.event.shared.GwtEvent.Type<NewModulePositionHandler> getAssociatedType() {
// TODO Auto-generated method stub
return TYPE;
}
#Override
protected void dispatch(NewModulePositionHandler handler) {
handler.onNewModulePosition(this);
}
}
And it's time for implementation of my custom widget:
a) MyComp.java
import com.google.gwt.event.shared.GwtEvent;
public class NewModulePositionEvent extends GwtEvent<NewModulePositionHandler> {
private static final Type<NewModulePositionHandler> TYPE = new Type<NewModulePositionHandler>();
private final String m_Color;
public NewModulePositionEvent(String color) {
m_Color = color;
}
public static Type<NewModulePositionHandler> getType() {
return TYPE;
}
public String getColor() {
return m_Color;
}
#Override
public com.google.gwt.event.shared.GwtEvent.Type<NewModulePositionHandler> getAssociatedType() {
// TODO Auto-generated method stub
return TYPE;
}
#Override
protected void dispatch(NewModulePositionHandler handler) {
handler.onNewModulePosition(this);
}
}
b) MyCompClientRpc.java
import com.vaadin.shared.communication.ClientRpc;
public interface MyCompClientRpc extends ClientRpc {
// TODO example API
public void alert(String message);
public void changeColor(String color);
}
c) MyCompConnector.java
package com.example.locator.widgetset.client.mycomp;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Widget;
import com.vaadin.client.ui.AbstractComponentConnector;
import com.vaadin.shared.ui.Connect;
import com.example.locator.MyComp;
import com.example.locator.NewModulePositionEvent;
import com.example.locator.NewModulePositionHandler;
import com.example.locator.widgetset.client.mycomp.MyCompWidget;
import com.example.locator.widgetset.client.mycomp.MyCompServerRpc;
import com.vaadin.client.communication.RpcProxy;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.vaadin.shared.MouseEventDetails;
import com.vaadin.client.MouseEventDetailsBuilder;
import com.example.locator.widgetset.client.mycomp.MyCompClientRpc;
import com.example.locator.widgetset.client.mycomp.MyCompState;
import com.vaadin.client.communication.StateChangeEvent;
#Connect(MyComp.class)
public class MyCompConnector extends AbstractComponentConnector {
MyCompServerRpc rpc = RpcProxy
.create(MyCompServerRpc.class, this);
public MyCompConnector() {
registerRpc(MyCompClientRpc.class, new MyCompClientRpc() {
public void alert(String message) {
// TODO Do something useful
Window.alert(message);
}
public void changeColor(String color) {
getWidget().InitMap(color);
}
});
// TODO ServerRpc usage example, do something useful instead
getWidget().addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
final MouseEventDetails mouseDetails = MouseEventDetailsBuilder
.buildMouseEventDetails(event.getNativeEvent(),
getWidget().getElement());
rpc.clicked(mouseDetails);
}
});
getWidget().addNewModulePositionHandler(new NewModulePositionHandler() {
public void onNewModulePosition(NewModulePositionEvent event) {
// TODO Auto-generated method stub
rpc.newModulePosition(event.getColor());
}
});
}
#Override
protected Widget createWidget() {
return GWT.create(MyCompWidget.class);
}
#Override
public MyCompWidget getWidget() {
return (MyCompWidget) super.getWidget();
}
#Override
public MyCompState getState() {
return (MyCompState) super.getState();
}
#Override
public void onStateChanged(StateChangeEvent stateChangeEvent) {
super.onStateChanged(stateChangeEvent);
// TODO do something useful
final String color = getState().color;
getWidget().InitMap(color);
}
}
d) MyCompServerRpc.java
package com.example.locator.widgetset.client.mycomp;
import com.vaadin.shared.MouseEventDetails;
import com.vaadin.shared.communication.ServerRpc;
public interface MyCompServerRpc extends ServerRpc {
// TODO example API
public void clicked(MouseEventDetails mouseDetails);
public void newModulePosition(String color);
}
e) MyCompState.java
package com.example.locator.widgetset.client.mycomp;
public class MyCompState extends com.vaadin.shared.AbstractComponentState {
// TODO example state
public String color = "#000000";
}
And finally implementation of the widget:
f) MyCompWidget.java
package com.example.locator.widgetset.client.mycomp;
import org.vaadin.gwtgraphics.client.DrawingArea;
import org.vaadin.gwtgraphics.client.Line;
import org.vaadin.gwtgraphics.client.shape.Circle;
import org.vaadin.gwtgraphics.client.shape.Rectangle;
import com.example.locator.HasNewModulePositionHandlers;
import com.example.locator.NewModulePositionEvent;
import com.example.locator.NewModulePositionHandler;
import com.google.gwt.dev.util.collect.HashMap;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.touch.client.Point;
import com.example.locator.Module;
// TODO extend any GWT Widget
public class MyCompWidget extends DrawingArea implements HasNewModulePositionHandlers {
public static final String CLASSNAME = "mycomp";
public static double m_AreaWidth = 64.355;
public static double m_AreaHeight = 17.385;
public static int m_PictureWidth;
public static int m_PictureHeight;
public static double m_AreaToMapRatio;
public static double m_RouteWidth = 3.5;
public static double m_MainRouteCoordinateY = 8.0828;
public Circle circle;
//public HashMap<Integer, Module> ModuleMap = new HashMap<Integer, Module>();
public MyCompWidget(){
super(640, 320);
//ModuleMap.put(666, new Module(666, 30.0, 8.08, new Circle((int)TranslateCoordinate(30.0), (int)TranslateCoordinate(8.0), 7)));
//ModuleMap.put(15, new Module(15, 27.0, 8.08, new Circle((int)TranslateCoordinate(30.0), (int)TranslateCoordinate(8.0), 7)));
double xRatio = m_AreaWidth / 640;
double yRatio = m_AreaHeight / 320;
m_AreaToMapRatio = xRatio > yRatio ? xRatio : yRatio;
InitMap("#919491");
setStyleName(CLASSNAME);
}
public void InitMap(String color)
{
m_PictureWidth = (int)TranslateCoordinate(m_AreaWidth);
m_PictureHeight = (int)TranslateCoordinate(m_AreaHeight);
Rectangle rectangle = new Rectangle(0, 0, m_PictureWidth, m_PictureHeight);
rectangle.setFillColor(color);
add(rectangle);
Point point1Beg = new Point(0.0, 8.0828);
Point point1End = new Point(64.355, 8.0838);
Point point2Beg = new Point(20.2825, 8.0828);
Point point2End = new Point(20.2825, 17.385);
Point point3Beg = new Point(59.325, 0.0);
Point point3End = new Point(59.325, 8.0828);
point1Beg = TranslatePoint(point1Beg);
point1End = TranslatePoint(point1End);
point2Beg = TranslatePoint(point2Beg);
point2End = TranslatePoint(point2End);
point3Beg = TranslatePoint(point3Beg);
point3End = TranslatePoint(point3End);
Line line1 = new Line((int)point1Beg.getX(), (int)point1Beg.getY(), (int)point1End.getX(), (int)point1End.getY());
Line line2 = new Line((int)point2Beg.getX(), (int)point2Beg.getY(), (int)point2End.getX(), (int)point2End.getY());
Line line3 = new Line((int)point3Beg.getX(), (int)point3Beg.getY(), (int)point3End.getX(), (int)point3End.getY());
line1.setStrokeColor("#FFFFFF");
line2.setStrokeColor("#FFFFFF");
line3.setStrokeColor("#FFFFFF");
line1.setStrokeWidth((int)TranslateCoordinate(m_RouteWidth));
line2.setStrokeWidth((int)TranslateCoordinate(m_RouteWidth));
line3.setStrokeWidth((int)TranslateCoordinate(m_RouteWidth));
add(line1);
add(line2);
add(line3);
DrawWall(TranslateCoordinate(10.0));
DrawWall(TranslateCoordinate(20.0));
DrawWall(TranslateCoordinate(30.0));
DrawWall(TranslateCoordinate(40.0));
DrawWall(TranslateCoordinate(50.0));
DrawWall(TranslateCoordinate(60.0));
DrawDoor(3.0, 3.0);
DrawDoor(13.0, 3.0);
DrawDoor(23.0, 3.0);
DrawDoor(33.0, 3.0);
DrawDoor(43.0, 3.0);
DrawDoor(53.0, 3.0);
circle = new Circle((int)TranslateCoordinate(25.0), (int)TranslateCoordinate(8.0), 15);
add(circle);
}
public void DrawWall(double a_Place)
{
Line line = new Line((int)a_Place, 0, (int)a_Place, (int)TranslateCoordinate(m_AreaHeight));
line.setStrokeColor("#FFFFFF");
add(line);
}
public void DrawDoor(double a_Position, double a_Width)
{
double realDoorPositionY = m_MainRouteCoordinateY - (m_RouteWidth / 2);
int doorPositionYTop = (int)TranslateCoordinate(realDoorPositionY) - 1;
int doorPositionYBottom = (int)TranslateCoordinate(realDoorPositionY + m_RouteWidth) + 1;
Line line = new Line((int)TranslateCoordinate(a_Position), doorPositionYTop, (int)TranslateCoordinate(a_Position) + (int)TranslateCoordinate(a_Width), doorPositionYTop);
line.setStrokeColor("#000000");
line.setStrokeWidth(2);
add(line);
Line line2 = new Line((int)TranslateCoordinate(a_Position), doorPositionYBottom, (int)TranslateCoordinate(a_Position) + (int)TranslateCoordinate(a_Width), doorPositionYBottom);
line2.setStrokeColor("#000000");
line2.setStrokeWidth(2);
add(line2);
}
public Point TranslatePoint(Point a_Point)
{
Point translatedPoint = new Point(TranslateCoordinate(a_Point.getX()), TranslateCoordinate(a_Point.getY()));
return translatedPoint;
}
public double TranslateCoordinate(double a_Coordinate)
{
return (a_Coordinate) / (m_AreaToMapRatio);
}
public void Move(int id) {
//ModuleMap.get(id).GetCircle().setX(10 + circle.getX());
}
public HandlerRegistration addNewModulePositionHandler(
NewModulePositionHandler handler) {
return addHandler(handler, NewModulePositionEvent.TYPE);
}
private void someMethod() {
fireEvent(new NewModulePositionEvent("#000000"));
}
public void emulateEvent() {
someMethod();
}
}
g) HasNewModulesPositionHandlers.java
package com.example.locator;
import com.google.gwt.event.shared.HandlerRegistration;
public interface HasNewModulePositionHandlers {
// Attention! method returns HandlerRegistration, so that handler can be cancelled
public HandlerRegistration addNewModulePositionHandler(
NewModulePositionHandler handler);
}
If I compile the widgets set containing MyCompWidget and then run my application on glassfish I get the following message:
Widgetset 'com.example.locator.widgetset.LocatorWidgetset' does not contain implementation for com.example.locator.MyComp. Check its component connector's #Connect mapping, widgetsets GWT module description file and re-compile your widgetset. In case you have downloaded a vaadin add-on package, you might want to refer to add-on instructions.
If I cut
public void addNewModulePositionHandler(
NewModulePositionHandler handler) {
handlerManager.addHandler(NewModulePositionEvent.getType(), handler);
// TODO Auto-generated method stub
}
widget works properly (of course I have to comment out these lines from MyCompConnector as well):
getWidget().addNewModulePositionHandler(new NewModulePositionHandler() {
public void onNewModulePosition(NewModulePositionEvent event) {
// TODO Auto-generated method stub
rpc.newModulePosition(event.getColor());
}
});
Can anyone tell me where is the problem? It seems that compilation of the widget failes but I can't find any information about that.
Please, help me.
Thanks in advance.
Compilation problem is very clear: GWT compiler cannot fins source code for a specified java class. You add source files to GWT compiler scope in two steps:
*.java files must be accessible through classpath (eclipse gwt compiler automatically includes all source folders to classpath)
You need to tell GWT that it should consider your packages during compilation
Create .gwt.xml file in PARENT package (relative to your source files) with the following content (if your package is pkg1.pkg2.pkg3, then you should in package pkg1.pkg2 create file "Pkg3.gwt.xml", pkg = "pkg3", by convention pkg3 is typically named "client")
<module>
<source path="pkg3" />
</module>
!!!Be careful with letter cases, By convention those are the correct names.
Add to your widgetset.gwt.xml file "inherits" directive like that
<inherits name="pkg1.pkg2.Pkg3" />
!!! Pay attention to letter cases (P is capital in Pkg3, after file name Pkg3.gwt.xml), .gwt.xml is omitted here
Then, first of all, Vaadin uses GWT with a certain twist. I would recommend browsing through custom widgetset samples. You may need to understand how to propagate events to and from Vaadin-specific components. Below I explain how GWT event are supposed to be implemented and used. I'm not an expert in Vaadin, especially in advanced topics such as customizing widgetsets.
So, speaking of GWT.
Basically, you need to understand only two things to make (non-DOM, also knows as bitless) events work in GWT.
Code support
Event class. NewModulePositionEvent in your case.
Event Handler interface. NewModulePositionHandler in your case.
Feature interface (optional but advised). HasNewModulePositionHandlers in your case.
Usage pattern
Basically, the component that is supposed to fire event should create relevant Event object and pass it to the fireEvent method. All the logic to invoke necessary habdler is provided by EventBus (internally)
If you need to provide API to fire events externally (such as click() method for a Button), it should be done by providing special methods (do not expose internal stuff how exactly event is fired)
DOM events are special in details how they are created (by browser) and dispatched (they need to be explicitly enabled). Anyway, all the browser events are already implemented in GWT out of the box.
So, typical implementations for the above items: For the sake of clarity, I provide excerpts from our production code.
1) Event class
public class QuestionClickEvent extends GwtEvent<QuestionClickHandler> {
public QuestionClickEvent(SScript script, SQuestion question) {
super();
this.script = script;
this.question = question;
}
public static final Type<QuestionClickHandler> TYPE = new Type<QuestionClickHandler>();
// internal event state
private final SScript script;
private final SQuestion question;
#Override
public Type<QuestionClickHandler> getAssociatedType() {
return TYPE;
}
#Override
protected void dispatch(QuestionClickHandler handler) {
handler.onQuestionClicked(this);
}
// provide access to internal event state
public SScript getScript() {
return script;
}
public SQuestion getQuestion() {
return question;
}
}
2) Handler interface
public interface QuestionClickHandler extends EventHandler {
public void onQuestionClicked(QuestionClickEvent event);
}
3) Feature interface
public interface HasQuestionClickHandlers {
// Attention! method returns HandlerRegistration, so that handler can be cancelled
public HandlerRegistration addQuestionClickHandler(
QuestionClickHandler handler);
}
4) Your widget/component
public class SummaryPanel extends Widget implements HasQuestionClickHandlers {
// blah-blah-blah
// implement your handler registration method
#Override
public HandlerRegistration addQuestionClickHandler(
QuestionClickHandler handler) {
return addHandler(handler, QuestionClickEvent.TYPE);
}
// blah-blah-blah
private someMethod() {
// suddenly you realized that you need to to fire your event
fireEvent(new QuestionClickEvent(script, question));
}
// sample external API method
public void emulateEvent() {
someMethod();
}
}
And finally usage example:
SummaryPanel summary = new SummaryPanel();
summary.addQuestionClickHandler(new QuestionClickHandler() {
#Override
public void onQuestionClicked(QuestionClickEvent event) {
// your reaction goes here
}
});