This website uses cookies for visitor traffic analysis. By using the website, you agree with storing the cookies on your computer.More information

Posts tagged: JVx

JVx Reference, Events

Let's talk about events and event handling in JVx.

What are events...

Events are an important mechanism no matter to what programming language or framework you turn to. It allows us to react on certain actions and "defer" actions until something triggered them. Such triggers can be anything, like a certain condition is hit in another thread, the user clicked a button or another action has finally finished. Long story short, you get notified that something happened, and that you can now do something.

...and why do I need to handle them?

Well, you can't skip events, they are a cornerstone of JVx. Theoretically, you could use JVx without using any of its events, but you would not only miss out on a lot of functionality but also be unable to do anything useful. But don't worry, understanding the event system is easy, using it even easier.

Terminology

For JVx the following terminology applies: An event is a property of an object, you can register listeners on that event which will get invoked if the event is dispatched (fired). Every event consists of the EventHandler class which allows to register, remove and manage the listeners and also dispatches the events, meaning invoking the listeners and notifying them that the event occurred. There is no single underlying listener interface.

Within the JVx framework, every event-property of an object does start with the prefix "event" to make it easily searchable and identifiable. But enough dry talk, let's get started.

Attaching listeners as class

The easiest way to get notified of events is to attach a class (which is implementing the listener interface) to an event as listener, like this:

public class MainFrame extends UIFrame
{
    public MainFrame()
    {
        super();
       
        UIButton button = new UIButton("Click me!");
        button.eventAction().addListener(new ActionListener());
       
        setLayout(new UIBorderLayout());
        add(button, UIBorderLayout.CENTER);
    }
}

private static final class ActionListener implements IActionListener
{
    public void action(UIActionEvent pActionEvent) throws Throwable
    {
        System.out.println("Button clicked!");
    }
}

Attaching listeners as inlined class

Of course we can inline this listener class:

public class MainFrame extends UIFrame
{
    public MainFrame()
    {
        super();
       
        UIButton button = new UIButton("Click me!");
        button.eventAction().addListener(new IActionListener()
        {
            public void action(UIActionEvent pActionEvent) throws Throwable
            {
                System.out.println("Button clicked!");
            }
        });
       
        setLayout(new UIBorderLayout());
        add(button, UIBorderLayout.CENTER);
    }
}

Attaching listeners JVx style

So far, so normal. But in JVx we have support to attach listeners based on reflection, like this:

public class MainFrame extends UIFrame
{
    public MainFrame()
    {
        super();
       
        UIButton button = new UIButton("Click me!");
        button.eventAction().addListener(this, "doButtonClick");
       
        setLayout(new UIBorderLayout());
        add(button, UIBorderLayout.CENTER);
    }
   
    public void doButtonClick(UIActionEvent pActionEvent) throws Throwable
    {
        System.out.println("Button clicked");
    }
}

What is happening here is that, internally, a listener is created which references the given object and the named method. This allows to easily add and remove listeners from events and keeping the classes clean by allowing to have all related event listeners in one place and without additional class definitions.

Attaching listeners as lambdas

Yet there is more, we can of course attach lambdas to the events as listeners, too:

public class MainFrame extends UIFrame
{
    public MainFrame()
    {
        super();
       
        UIButton button = new UIButton("Click me!");
        button.eventAction().addListener((pActionEvent) -> System.out.println("Button clicked"));
       
        setLayout(new UIBorderLayout());
        add(button, UIBorderLayout.CENTER);
    }
}

Attaching listeners as method references

And last but not least, thanks to the new capabilities of Java 1.8, we can also use method references:

public class MainFrame extends UIFrame
{
    public MainFrame()
    {
        super();
       
        UIButton button = new UIButton("Click me!");
        button.eventAction().addListener(this::doButtonClick);
       
        setLayout(new UIBorderLayout());
        add(button, UIBorderLayout.CENTER);
    }
   
    private void doButtonClick(UIActionEvent pActionEvent) throws Throwable
    {
        System.out.println("Button clicked");
    }
}

Parameters or no parameters? To throw or not to throw?

By default we actually support two different classes of listeners, the specified event/listener interface itself, and (javax.rad.util.)IRunnable. Which means that you can also attach methods which do not have any parameters, like this:

public class MainFrame extends UIFrame
{
    public MainFrame()
    {
        super();
       
        UIButton button = new UIButton("Click me!");
        button.eventAction().addListener(this::doButtonClickNoParameters);
        button.eventAction().addListener(this::doButtonClickWithParameters);
       
        setLayout(new UIBorderLayout());
        add(button, UIBorderLayout.CENTER);
    }
   
    private void doButtonClickNoParameters() throws Throwable
    {
        System.out.println("Button clicked");
    }

    private void doButtonClickWithParameters(UIActionEvent pActionEvent) throws Throwable
    {
        System.out.println("Button clicked");
    }
}

Additionally, all listeners and IRunnable itself do support to throw Throwable, which is then handled inside the EventHandler. So you are very flexible when it comes to what methods you can attach and use as listeners.

Creating your own events

You can, of course, create your own EventHandlers and listeners to create your own events. All you need are two classes, an extension of EventHandler and a listener interface.

public class CustomEvent extends EventHandler
{
    public CustomEvent()
    {
        super(ICustomListener.class);
    }
}

public interface ICustomListener
{
    public void somethingHappened(String pName);
}

And that's it, from here on you can use it:

CustomEvent event = new CustomEvent();
event.addListener((pName) -> System.out.println(pName + " 1"));
event.addListener((pName) -> System.out.println(pName + " 2"));
event.addListener((pName) -> System.out.println(pName + " 3"));

event.dispatchEvent("Adam");

More methods!

You can also use an interface for listeners which has multiple methods, specifying in the constructor which method to invoke:

public class CustomEvent extends EventHandler
{
    public CustomEvent()
    {
        super(ICustomListener.class, "somethingOtherHappened");
    }
}

public interface ICustomListener
{
    public void somethingHappened(String pName);
    public void somethingOtherHappened(String pName, BigDecimal pValue);
    public void nothingHappened();
}

Now every time the event is dispatched, the somethingOtherHappened method will be invoked. Anyway, don't use this. The upside of having a "simple" listener interface with just one method (SAM-type) is that it allows to use lambdas with it. A listener interface with multiple methods won't allow this.

In JVx we reduced our listener interfaces to just one method (in a backward compatible way) to make sure all events can be used with lambdas.

Fire away!

That's it for this short reference sheet, that is how our event system can and should be used. Of course, there is much more to it under the hood, for example listeners being wrapped in proxy classes, reflection used for invoking methods and some more stuff. If you feel adventurous, be my guest and have a good look at the internals of EventHandler, it is quite an interesting read.

Mavenized everything

We're happy to announce that all our projects are available as Maven artifacts.
Not all of our projects are public and aren't available in public Maven repositories, but we offer our own nexus for all this projects.

Which projects aren't public?

  • Vaadin Charts UI
  • Vaadin responsive application frame
  • Application client
  • Application server
  • Application Services
  • JavaFX mobile UI
  • Oracle Forms extension

We provide snapshot and release artifacts. All other - public - projects are available via maven central as release or snapshot artifacts.

  • JVx
  • JVx EE
  • Vaadin UI
  • JavaFX UI
  • Headless UI
  • Online help
  • JVx mobile

Our private Maven repository is available on a subscription basis. This doesn't mean that our private projects aren't open source projects, but we don't offer snapshot or release artifacts for them!

Maven central: JVx.web snapshots

Our JVx headless UI (aka JVx.web) implementation is available as maven snapshot:

<dependency>  
  <groupId>com.sibvisions.web</groupId>    
  <artifactId>headless</artifactId>  
  <version>1.2-SNAPSHOT</version>
</dependency>

Don't forget the snapshot repository:

<repository>  
  <id>sonatype-nexus-snapshots</id>    
  <name>Sonatype Snapshots</name>  
  <url>https://oss.sonatype.org/content/repositories/snapshots/</url>
</repository>

Maven central: JVx.mobile snapshots

Our JVx mobile project is available as maven snapshot:

<dependency>  
  <groupId>com.sibvisions.mobile</groupId>    
  <artifactId>mobile-server</artifactId>  
  <version>1.0.1-SNAPSHOT</version>
</dependency>

and only the API

<dependency>  
  <groupId>com.sibvisions.mobile</groupId>    
  <artifactId>mobile-api</artifactId>  
  <version>1.0.1-SNAPSHOT</version>
</dependency>

Don't forget the snapshot repository:

<repository>  
  <id>sonatype-nexus-snapshots</id>    
  <name>Sonatype Snapshots</name>  
  <url>https://oss.sonatype.org/content/repositories/snapshots/</url>
</repository>

Maven central: JavaFX UI snapshots

Our JavaFX UI for JVx is available as maven snapshot:

<dependency>  
  <groupId>com.sibvisions.jvx</groupId>    
  <artifactId>jvxfx</artifactId>  
  <version>1.2-SNAPSHOT</version>
</dependency>

or only JavaFX extensions

<dependency>  
  <groupId>com.sibvisions.jvx</groupId>    
  <artifactId>jfxtensions</artifactId>  
  <version>1.2-SNAPSHOT</version>
</dependency>

and don't forget the snapshot repository:

<repository>  
  <id>sonatype-nexus-snapshots</id>    
  <name>Sonatype Snapshots</name>  
  <url>https://oss.sonatype.org/content/repositories/snapshots/</url>
</repository>

JVx 2.5.1 is available

We're happy to announce that JVx 2.5.1 is available.

What's new?

  • Push-light

    Our push support has nothing to do with Websockets. It's a technology independent solution for JVx. The Push-light mechanism is available on server-side and enables you to send objects from the server to the client. If you use a direct connection betwenn client and server, the objects wil be sent immediate (e.g. vaadin UI). If you use a serialized connection, the objects will be sent with next client call or alive check.

    The API is simple:

    SessionContext.publishCallBackResult("MESSAGE", "Please logout!");

    or, in a Thread

    final ICallBackBroker broker = SessionContext.getCurrentInstance().getCallBackBroker();

    Thread th = new Thread(new Runnable()
    {
        public void run()
        {
            try
            {
                int i = 0;

                while (isMessageLoopEnabled(i))
                {
                    Thread.sleep(200);
                   
                    broker.publish("MESSAGE", getMessage(i++));
                }
            }
            catch (InterruptedException ie)
            {
                //done
            }
        }
    });
    th.start();

    It's also possible to publish to all clients, via ICallBackBroker.

    The client code is short and simple:

    connection.addCallBackResultListener(new ICallBackResultListener()
    {
        public void callBackResult(CallBackResultEvent pEvent)
        {
            if ("MESSAGE".equals(pEvent.getInstruction()))
            {
                showMessage((String)pEvent.getObject());
            }
        }
    });

    More details: Tickets #25, #1635

  • H2 DB support

    We support H2 with a custom H2DBAccess. The auto detection works with URLs: jdbc:h2:.

  • SQLite DB support

    We support SQLite with a custom SQLiteDBAccess. The auto detection works with URLs: jdbc:sqlite:.

  • MySql limit support

    Read more...

  • Life-cylcle object method inheritance
  • Pie control
  • Set individual cells of a table readonly
  • Connection retries

    We try to re-send requests, if errors occur during transmission. This feature will be available for serialized connections only.

  • Security improvements

    see Tickets: #1605, #1606, #630.

  • Session validator

    We introduced ISessionValidator interface. It allows you to cancel the session after successful authentication. You don't need a custom security manager for this!
    Simply configure the validator in your config.xml:

    <lifecycle>
      <mastersession postAuthClass="com.sibvisions.apps.server.MySessionValidator">
    com.sibvisions.apps.demo.MySession
      </mastersession>
    </lifecycle>
  • API changes

    ICellFormat got a Style attribute and the createCellFormat of IFactory got one more parameter.

The full changelog is available here.

JVx 2.5 - summer release

The next JVx release will be version 2.5. It will be available by the end of this week (beginning of July). It's a really cool release because JVx got awesome new features. We had to change the API a little bit but it shouldn't be a problem for your existing applications.

What will be interesting?

  • Push-light

    Our push support has nothing to do with Websockets. It's a technology independent solution for JVx. The Push-light mechanism is available on server-side and enables you to send objects from the server to the client. If you use a direct connection betwenn client and server, the objects wil be sent immediate (e.g. vaadin UI). If you use a serialized connection, the objects will be sent with next client call or alive check.

    The API is simple:

    SessionContext.publishCallBackResult("MESSAGE", "Please logout!");

    or, in a Thread

    final ICallBackBroker broker = SessionContext.getCurrentInstance().getCallBackBroker();

    Thread th = new Thread(new Runnable()
    {
        public void run()
        {
            try
            {
                int i = 0;

                while (isMessageLoopEnabled(i))
                {
                    Thread.sleep(200);
                   
                    broker.publish("MESSAGE", getMessage(i++));
                }
            }
            catch (InterruptedException ie)
            {
                //done
            }
        }
    });
    th.start();

    It's also possible to publish to all clients, via ICallBackBroker.

    The client code is short and simple:

    connection.addCallBackResultListener(new ICallBackResultListener()
    {
        public void callBackResult(CallBackResultEvent pEvent)
        {
            if ("MESSAGE".equals(pEvent.getInstruction()))
            {
                showMessage((String)pEvent.getObject());
            }
        }
    });

    More details: Tickets #25, #1635

  • H2 DB support

    We support H2 with a custom H2DBAccess. The auto detection works with URLs: jdbc:h2:.

  • SQLite DB support

    We support SQLite with a custom SQLiteDBAccess. The auto detection works with URLs: jdbc:sqlite:.

  • MySql limit support

    Read more...

  • Life-cylcle object method inheritance
  • Pie control
  • Set individual cells of a table readonly
  • Connection retries

    We try to re-send requests, if errors occur during transmission. This feature will be available for serialized connections only.

  • Security improvements

    see Tickets: #1605, #1606, #630.

  • API changes

    ICellFormat got a Style attribute and the createCellFormat of IFactory got one more parameter

JVx and MySQL, Limited Edition

If you work with JDBC and MySQL, you will most likely be aware of one shortcoming: MySQL can not stream the results from a query (well, actually it can, but the feature is quite limited). That means that up until now JVx has always received and stored the full result set in memory which it received from MySQL. No paging was performed as it was done in the Oracle implementation.

Limit to the rescue!

MySQL does support the limit clause, which allows to limit the results to either a certain number of rows, or a certain range of rows. How does it look like?

SELECT
    ID,
    NAME
FROM
    TEST
WHERE
    NAME LIKE 'Hans%'
LIMIT 5, 10;

This will fetch the data starting by the 5th row up to the 15th row, so it will skip the first five rows and then return the next ten. As this is a database builtin, no additional data is send over the wire except the actual requested rows. This is perfect if you want to limit your queries, for example, because you know that you don't need more than 5 rows even though there are 50,000 rows.

Fetch all the things!

With the old behavior, without limit clause, the JDBC MySQL driver would fetch the complete result of the query and only we would do some cutting on it (mainly dropping not needed rows at the start). That meant that the complete result set was always loaded into memory, which itself might have caused that you were unable to execute certain queries, especially if they contained bigger blob columns.

Limit all the things!

With the new behavior, the limit clause is appended to the query as needed, which means that the JDBC MySQL driver has to load a lot less data and a lot less data is send over the wire.

The MySQL giveth, the MySQL taketh away...

But there is an additional cost associated with the usage of the limit clause. Because the fetches are separate statements, all rows leading up to the beginning row have to be selected, too. Let us return to our first example, the query of the TEST table. We only want 10 rows starting from the 5th row, that means our result set only contains 10 rows. However, MySQL has (obviously) to query, select and discard the first five rows so that it can start sending us the rows that we actually want. That means that the cost of selecting pages increases. Off to pretty graphics!

Impressions

Note that the fetch time is accumulative.

  • Blue: The original implementation which does perform only one fetch of all data. In this case it is quite fast, but depending on the query and data you could wait a long time for the initial fetch, if it was possible at all.
  • Orange: The current implementation with quite a worst case scenario, it gradually fetches page after page with a row count of 50. As you can see the fetch time gradually increases, but as you can also see the initial fetches are fast.
  • Yellow: An optimization experiment which increases the fetched row count dynamically.

Let us look at this again in detail, to be exact the fetching of the first 1500 rows.

Impressions

What we see here is quite good news, actually, because with the new implementation with the limit clause, you can consecutively fetch 600 rows in the same time as the fetching of the 4400 rows with the old implementation. The big difference here is that the first set of ~113 rows returns close to immediately and consecutive fetches are equally fast. This is awesome because we can now display initial data faster, even few it is fewer data in the end and slows down the more data is fetched afterwards.

Improve all the things!

As you can see from the charts, we already did a short experiment to improve this further, and we are confident that we can implement such a solution which dynamically fetches more rows to reduce the overall fetch time while still preserving that the first rows are displayed fast, further improving GUI responsiveness.

Effiziente Software Entwicklung mit JavaFX und JVx

javaaktuell2016 Ein spannender Artikel über JVx und JavaFX ist im aktuellen JavaAktuell zu finden.

Der Artikel wurde von Roland Hörmann verfasst und behandelt das Thema Effiziente Software Entwicklung mit Java und insbesondere mit JavaFX bzw. dem OpenSource Java Framework JVx.

Wer das Magazin nicht zur Hand hat, kann den Artikel auch von hier laden und sofort lesen.

Use OBridge together with JVx

OBridge is a nice Java FOSS project. The description according to the website:

OBridge generates standard Java source code for calling PL/SQL stored procedures and functions.

It's focus is on Oracle but this wasn't a limitation for us to test it with JVx.

Most of you know that JVx has generic support for procedure/function calls which is DB independent. The implementation is not really type-safe but it's simple.
If type-safety is preferred, you could use OBridge for your application.

I write about this library, because it's super small and simple. We love small and simple things :)

Assume, we have following PL/Sql procedure:

CREATE OR REPLACE PROCEDURE execProcedure(pNumber IN OUT NUMBER,
                                          pInText IN VARCHAR2,
                                          pOutText OUT VARCHAR2) IS
  nr NUMBER := pNumber;
BEGIN
  pOutText := 'Out: '|| pOutText ||' In: '|| pInText;

  pNumber := pNumber + pNumber;
END execProcedure;

and function:

CREATE OR REPLACE FUNCTION execFunction(pNumber IN OUT NUMBER,
                                        pInText IN VARCHAR2,
                                        pOutText OUT VARCHAR2) RETURN VARCHAR2 IS
  res VARCHAR2(200);
  nr NUMBER := pNumber;
BEGIN
  pOutText := 'Out: '|| pOutText ||' In: '|| pInText;

  pNumber := pNumber + pNumber;

  RETURN 'IN-Param Nr: '|| nr;
END execFunction;

 

With JVx, the procedure and function call will look like following JUnit test:

@Test
public void testCall() throws Exception
{
    DBAccess dba = DBAccess.getDBAccess("jdbc:oracle:thin:@localhost:xe", "test", "test");
    dba.open();
   
    /**
     * Procedure call.
     */

    OutParam ouTextParam = new OutParam(InOutParam.SQLTYPE_VARCHAR);
    dba.executeProcedure("execProcedure", BigDecimal.valueOf(25),
                         "Hello JVx' procedure", ouTextParam);

    Assert.assertEquals("Out:  In: Hello JVx' procedure", ouTextParam.getValue());

    /**
     * Function call.
     */

   
    ouTextParam = new OutParam(InOutParam.SQLTYPE_VARCHAR);
    Object oResult = dba.executeFunction("execFunction", Types.VARCHAR,
                                         BigDecimal.valueOf(25),
                                         "Hello JVx' function", ouTextParam);
   
    Assert.assertEquals("IN-Param Nr: 25", oResult);
    Assert.assertEquals("Out:  In: Hello JVx' function", ouTextParam.getValue());
}

 

and the same with OBridge:

@Test
public void testCall() throws Exception
{
    DBAccess dba = DBAccess.getDBAccess("jdbc:oracle:thin:@localhost:1521:xe", "test", "test");
    dba.open();
   
    /**
     * Procedure call.
     */

    Execprocedure proc = ProceduresAndFunctions.execprocedure(BigDecimal.valueOf(35),
                                           "Hello OBridge procedure", dba.getConnection());
   
    Assert.assertEquals("Out:  In: Hello OBridge procedure", proc.getPouttext());

    /**
     * Function call.
     */

   
    Execfunction func = ProceduresAndFunctions.execfunction(BigDecimal.valueOf(35),
                                            "Hello OBridge function", dba.getConnection());
   
    Assert.assertEquals("IN-Param Nr: 35", func.getFunctionReturn());
    Assert.assertEquals("Out:  In: Hello OBridge function", func.getPouttext());
}

 

The OBridge code saves two LoC for the call, but it needs some additional classes and packages in your application. If you change your procedure or function definition in the database, you have to recreate the Java files.
This is not needed with pure JVx, but it's your choice.

The code generation is not tricky, simply follow the official documentation. Our steps:

  • Create the file config.xml in the working directory of your project
    <?xml version="1.0" encoding="UTF-8"?>

    <configuration>
        <jdbcUrl>jdbc:oracle:thin:test/test@localhost:1521:xe</jdbcUrl>
        <sourceRoot>./src/</sourceRoot>
        <rootPackageName>com.sibvisions.apps.obridge.db</rootPackageName>
        <packages>
            <entityObjects>objects</entityObjects>
            <converterObjects>converters</converterObjects>
            <procedureContextObjects>context</procedureContextObjects>
            <packageObjects>packages</packageObjects>
        </packages>
    </configuration>

  • Run the main class: org.obridge.OBridge with argument: -c config.xml
    (or use -c fullqualified_path_to_config.xml)
 

If you love our generic built-in solution, you don't need OBridge but if you prefer type-safety it's definitely an option.