arrow_back history picture_as_pdf This page is read only. You can view the source, but not change it. Ask your administrator if you think this is wrong. ~~NOTRANS~~ ~~Title: JVx code snippets~~ We have a list of useful code snippets for you. Simply use them for your application. All snippets are free to use and licensed under [[https://www.apache.org/licenses/LICENSE-2.0|Apache 2.0]]. ==== Test DBStorages without Lifecycle objects ==== Access a DBStorage without JVx Server, Lifecycle Object, Security e.g. for Unit tests <file java> //configure DB access DBAccess dba = new DBAccess(); dba.setUrl("..."); dba.setUsername("user"); dba.setPassword("pwd"); dba.open(); //configure storage for Table USERS DBStorage dbs = new DBStorage(); dbs.setFromClause("USERS"); dbs.setDBAccess(dba); dbs.open(); //direct object connection for direct method calls DirectObjectConnection con = new DirectObjectConnection(); con.put("users", dbs); //client connection for RemoteDataBook access to the storage MasterConnection macon = new MasterConnection(con); macon.open(); RemoteDataSource rds = new RemoteDataSource(macon); rds.open(); RemoteDataBook rdbApps = new RemoteDataBook(); rdbApps.setDataSource(rds); rdbApps.setName("users"); rdbApps.open(); </file> ==== A custom Application without menu, toolbar, ... ==== Sometimes we need an application without overhead, e.g for Vaadin UI. <file java SimpleApplication.java> public class SimpleApplication extends Application implements IExceptionListener { //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Class members //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /** the main/content panel. */ private UIPanel panMain; //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Initialization //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /** * Creates a new instance of <code>SimpleApplication</code>. * * @param pLauncher the launcher */ public SimpleApplication(UILauncher pLauncher) { super(pLauncher); setName("Simple application"); init(); } /** * Initializes the application. */ private void init() { ExceptionHandler.addExceptionListener(this); panMain = new UIPanel(); panMain.setLayout(new UIBorderLayout()); panMain.add(YOUR COMPONENT, UIBorderLayout.CENTER); setLayout(new UIBorderLayout()); add(panMain); } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Interface implementation //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ public IContainer getContentPane() { return panMain; } public <OP> IContent showMessage(OP pOpener, int pIconType, int pButtonType, String pMessage, String pOkAction, String pCancelAction) throws Throwable { System.out.println(pMessage); return null; } public void handleException(Throwable pThrowable) { System.out.println(CommonUtil.dump(pThrowable, false)); } } // SimpleApplication </file> ==== Test your business logic with JUnit ==== Tests our business logic without an application server, but with our Lifecycle objects. We test our server code without specific configuration or modifications for unit tests. Business Object: <file java UserRegistration.java> public class UserRegistration { /** * Removes/Unregisters a user and all its content. * * @param pUserName the user name * @throws Exception if the user can not be deleted */ public void delete(String pUserName) throws Exception { try { DBAccess dba = (DBAccess)SessionContext.getCurrentSession().get("newDBAccess"); DBStorage dbsUser = new DBStorage(); dbsUser.setDBAccess(dba); dbsUser.setWritebackTable("USERS"); dbsUser.open(); List<IBean> liBeans = dbsUser.fetchBean(new Equals("USERNAME", pUserName), null, 0, -1); //the username is unique and it's not possible that a user exists //more than once! if (liBeans.size() == 1) { //delete the user (db will cascade all user-data) dbsUser.delete(liBeans.get(0)); } else { throw new SecurityException("User '" + pUserName + "' was not found!"); } } catch (Throwable th) { throw new SecurityException("It's not possible to delete the user!", th); } } } // UserRegistration </file> A standard Lifecycle Object: <file java Session.java> public class Session extends GenericBean { //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // User-defined methods //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /** * Creates a new database access object. * * @return the new database access object * @throws Exception if the connection can not be opened */ public DBAccess getNewDBAccess() throws Exception { DBAccess dba = DBAccess.getDBAccess(DBSecurityManager.getCredentials( SessionContext.getCurrentSessionConfig())); dba.open(); return dba; } /** * Returns the access to the database. * * @return the access to the database * @throws Exception if the datasource can not be opened */ public DBAccess getDBAccess() throws Exception { DBAccess dba = (DBAccess)get("dBAccess"); if (dba == null) { dba = getNewDBAccess(); put("dBAccess", dba); } return dba; } /** * Gets the user registration business object. * * @return the business object for user registrations */ public UserRegistration getRegistration() { UserRegistration ureg = (UserRegistration)get("registration"); if (ureg == null) { ureg = new UserRegistration(); put("registration", ureg); } return ureg; } } // Session </file> Unit Test: <file java> /** * Tests the our delete method from the user registration object. * * @throws Throwable if the test fails */ @Test public void testDelete() throws Throwable { AbstractConnection con = createConnection(null); try { //delete user with the name "unknownuser" con.call("registration", "delete", "unknownuser"); Assert.fail("User 'unknownuser' found!"); } catch (SecurityException se) { Assert.assertEquals("User 'unknownuser' was not found!", se.getMessage()); } con.close(); } /** * Creates a new connection. * * @param pConProps additional connection properties * @return the connection * @throws Throwable if the connection can not be opened */ private AbstractConnection createConnection(Hashtable<String, String> pConProps) throws Throwable { MasterConnection macon = new MasterConnection(new DirectServerConnection()); macon.setApplicationName("app"); macon.setUserName("user"); macon.setPassword("pwd"); if (pConProps != null) { for (Map.Entry<String, String> entry : pConProps.entrySet()) { macon.setProperty(entry.getKey(), entry.getValue()); } } macon.open(); return macon; } </file> ==== A very simple AbstractMemStorage implementation ==== A server side memory storage with the column names: ID, NAME, PATH. The column PATH is not visible on the client-side, but is important for server-side. If "error" is set as NAME, an Exception is thrown! <file java SimpleMemStorage.java> public class SimpleMemStorage extends AbstractMemStorage { //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Abstract methods implementation //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /** * {@inheritDoc} */ @Override public RowDefinition getRowDefinition() throws ModelException { RowDefinition rowdef = new RowDefinition(); rowdef.addColumnDefinition(new ColumnDefinition("ID", new BigDecimalDataType())); rowdef.addColumnDefinition(new ColumnDefinition("NAME", new StringDataType())); rowdef.addColumnDefinition(new ColumnDefinition("PATH", new StringDataType())); rowdef.setPrimaryKeyColumnNames(new String[] {"ID"}); rowdef.setColumnView(null, new ColumnView("ID", "NAME")); return rowdef; } /** * {@inheritDoc} */ @Override public void loadData(MemDataBook pBook, ICondition pFilter) throws ModelException { pBook.deleteAllDataRows(); pBook.insert(false); pBook.setValues(new String[] {"ID", "NAME", "PATH"}, new Object[] {BigDecimal.valueOf(0), "First", "/home/first"}); pBook.insert(false); pBook.setValues(new String[] {"ID", "NAME", "PATH"}, new Object[] {BigDecimal.valueOf(1), "Second", "/home/second"}); pBook.insert(false); pBook.setValues(new String[] {"ID", "NAME", "PATH"}, new Object[] {BigDecimal.valueOf(2), "Third", "/home/third"}); } /** * {@inheritDoc} */ @Override public void insert(DataBookEvent pEvent) throws ModelException { if ("error".equals(pEvent.getChangedDataBook().getValueAsString("NAME"))) { throw new ModelException("not allowed"); } } @Override public void delete(DataBookEvent pEvent) { } @Override public void update(DataBookEvent pEvent) throws ModelException { if ("error".equals(pEvent.getChangedDataBook().getValueAsString("NAME"))) { throw new ModelException("not allowed"); } } } // SimpleMemStorage </file> ==== Change XML files very fast ==== Our XML file <file xml> <server> <!-- Test: STARTPORT --> <startport>2001</startport> <audio>off</audio> <serial>COM1</serial> <domain>JVx</domain> </server> </file> Change it: <file java> XmlNode xmnRead = readXml("simple.xml"); xmnRead.setNode("/server/audio", null); xmnRead.setNode("/server/domain", "www.sibvisions.com"); writeXml(xmnRead, "simple.xml"); </file> ==== EventHandler without Listener interface ==== Event definition: <file java> /** the event handler for captured (the event has one parameter: byte[]). */ private CallableHandler chCaptured = new CallableHandler(byte[].class); /** the event handler for canceled (the event has no parameter). */ private CallableHandler chCanceled = new CallableHandler(); </file> Event access: <file java> /** * Gets the captured event handler. * * @return the event handler */ public CallableHandler eventCaptured() { return chCaptured; } /** * Gets the canceled event handler. * * @return the event handler */ public CallableHandler eventCanceled() { return chCanceled; } </file> Dispatch events: <file java> chCaptured.dispatchEvent(byData); chCancel.dispatchEvent(); </file> Listener registration: <file java> object.eventCaptured().addListener(this, "doCapture"); public void doCapture(byte[] pImage) throws Exception { //... } </file> ==== EventHandler with Listener interface ==== The interface: <file java IRemoteApplicationListener.java> public interface IRemoteApplicationListener { //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Method definitions //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /** * Invoked when login was successful. * * @param pApplication the application */ public void afterLogin(RemoteApplication pApplication); /** * Invoked when logout was successful. * * @param pApplication the application */ public void afterLogout(RemoteApplication pApplication); } // IRemoteApplicationListener </file> The EventHandler: <file java RemoteApplicationHandler.java> public class RemoteApplicationHandler extends RuntimeEventHandler<IRemoteApplicationListener> { //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Initialization //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /** * Constructs a new RemoteApplicationHandler. * * @param pListenerMethodName the method to be called inside the interface. */ public RemoteApplicationHandler(String pListenerMethodName) { super(IRemoteApplicationListener.class, pListenerMethodName); } } // RemoteApplicationHandler </file> Event access: <file java> /** the "after login" event. */ private RemoteApplicationHandler eventAfterLogin; /** the "after logout" event. */ private RemoteApplicationHandler eventAfterLogout; /** * Gets the event handler for the after login event. * * @return the event handler */ public RemoteApplicationHandler eventAfterLogin() { if (eventAfterLogin == null) { eventAfterLogin = new RemoteApplicationHandler("afterLogin"); } return eventAfterLogin; } /** * Gets the event handler for the after logout event. * * @return the event handler */ public RemoteApplicationHandler eventAfterLogout() { if (eventAfterLogout == null) { eventAfterLogout = new RemoteApplicationHandler("afterLogout"); } return eventAfterLogout; } </file> Dispatch Events: <file java> /** * Fires the after logout event. */ protected void afterLogout() { if (eventAfterLogout != null) { eventAfterLogout.dispatchEvent(this); } } /** * Fires the after login event. */ protected void afterLogin() { if (eventAfterLogin != null) { eventAfterLogin.dispatchEvent(this); } } </file> Listener registration: <file java> app.eventAfterLogin().addListener(this, "doAfterLogin"); app.eventAfterLogout().addListener(this, "doAfterLogout"); //We do not need the parameter public void doAfterLogin() { } //We do not need the parameter public void doAfterLogout() { } </file>