Showing posts with label Vaadin. Show all posts
Showing posts with label Vaadin. Show all posts

Friday, January 18, 2019

Infinite lazy loading

Here's a short excerpt of Chapter 9 Lazy Loading of my book Data-Centric Applications with Vaadin 8.

Even though we have explained lazy loading by using the Grid component, we can use the same backend service method to implement custom UI components that support lazy loading. For example, you can use a VerticalLayout to add sets of, say, 10 components any time the user clicks a load more button at the bottom of the layout. In this case, you would need to keep track of the current offset and keep incrementing it until the service method returns less than 10 items.

The following is a simple UI component that shows how to implement this type of infinite lazy loading:

public class LazyLoadingVerticalLayout extends Composite {

    private CssLayout content = new CssLayout();
    private Button button = new Button("Load more...");
    private int offset;
    private int pageSize;

    public LazyLoadingVerticalLayout(int pageSize) {
        this.pageSize = pageSize;
  
        button.setStyleName(ValoTheme.BUTTON_BORDERLESS_COLORED);
  
        VerticalLayout mainLayout = new VerticalLayout(content, button);
        setCompositionRoot(mainLayout);

        button.addClickListener(e -> loadMore());
        loadMore();
    }

    public void loadMore() {
        List<Call> calls = CallRepository.find(
                offset, pageSize, "", new HashMap<>());

        if (calls.size() < pageSize) {
            button.setVisible(false);
        }

        calls.stream()
                .map(call -> new Label(call.toString()))
                .forEach(content::addComponent);

        offset += pageSize;
    }
}

Notice how the loadMore method keeps adding components to the content layout until there are no more results to add, at which point the Load more... button is hidden from the UI.

The following screenshot shows this component in action:


You can learn more about lazy loading and many other topics related to web development with Vaadin in my book Data-Centric Applications with Vaadin 8 available at amazon.compacktpub.com, and many other online bookstores.
Share:

Wednesday, January 2, 2019

Hello, World in Vaadin 10+

Vaadin is a set of tools to create web applications tailored to both, client-side and server-side developers. If you are, say, a JavaScript Developer, you can use Vaadin Components in any HTML document. If you are a Java Developer, you can use the provided Java API and forget about coding any HTML or JavaScript at all.

In this article, I'll show you how to create the famous Hello, World application using the Java Programming Language and Vaadin 12 (also valid for Vaadin 10 and 11). Get comfortable, make sure you have Maven installed, fire up your favorite IDE, and let's get started!

Start with a starter, obviously

Go to https://vaadin.com/start/latest and select Project Base. This is the most straightforward project starter and serves well as an initial point. Click Download and extract the zip file. You should get a directory with a Maven project in it. Import this project into your favorite IDE (mine is IntelliJ IDEA, by the way).

You should get a directory structure that looks similar to the following:


Let's not worry about the resources and webapp subdirectories for now. Also, I want you to get your hands dirty and implement the example app by yourself. However, it turns out the starter includes the MainView class with kind of a Hello, World application in it. So, let's get rid of the code in the MainView class by removing any annotations, extended classes, and code in the constructor. Go ahead and remove code until it looks like the following (or delete the file and create a new one):

package org.vaadin.alejandro; // use yours, of course

public class MainView {

    public MainView() {
    }

}

The project is ready. Let's add some code to it!

Add UI components to the web page

Think of the MainView class as the web page shown when you request the app in the web browser. Let's start by doing the simplest Hello, World app we can do with Vaadin–a web app that shows a greeting on the screen.

First off, we need the MainView class to be of a type that Vaadin recognizes as a UI component it can deal with. You have many options, but we will extend a popular class called VerticalLayout:

package org.vaadin.alejandro;

import com.vaadin.flow.component.orderedlayout.VerticalLayout;

public class MainView extends VerticalLayout {

    public MainView() {
    }

}

Now the MainView class has more powers. Check in your IDE some of the methods available in VerticalLayout. You can use the autocompletion feature of your IDE to quickly explore what's available:



What is a VerticalLayout, though? A VerticalLayout is a UI component that arranges other UI components (like buttons or grids) in a vertical fashion or a column if you wish. You do this by using the VerticalLayout.add(Component...) method. But first, we need to prepare the component we want to add to the VerticalLayout. Let's use a very simple one: Text. Go ahead and create a new instance of this class inside the constructor:

public MainView() {
    Text text = new Text("Hello, World!");
}

Now call the add(Component...) method to actually add the text component to the VerticalLayout:

public MainView() {
    Text text = new Text("Hello, World!");
    add(text);
}

Expose the view as a web page

To serve this class as a web page, you need to tell Vaadin you wish to do so. Doing this is super easy. Just annotate your MainView class with @Route:

@Route
public class MainView extends VerticalLayout {
    ...
}

The @Route annotation accepts an optional parameter to specify the actual route (the last part of the URL) you want to use to show this view. For example, @Route("hello") would make the view available at http://localhost:8080/hello. However, Vaadin uses a convention with the class name. Since our class is named MainView, Vaadin exposes the view at the context root (http://localhost:8080/). Moreover, if you add a class named CustomersView, for example, Vaadin exposes the view at http://localhost:8080/customers (note how the "View" part in the class name is ignored). Any other names are exposed using the class name. Just remember that you can override this by using the String parameter in the @Route annotation.

Deploy and run the web application

Since we used a Vaadin starter to create the project, the pom.xml file includes the Jetty Maven plug-in which allows you to use Maven to deploy and run the web application in a local Jetty server. The quickest way to run the application is by using a command line terminal and run:

mvn jetty:run

However, I recommend creating a run configuration in your IDE. A run configuration is like a shortcut inside the IDE to execute an action, for example, a Maven command. Most IDEs offer the possibility to create this from a Maven view that shows all the plugins and its corresponding goals. In IntelliJ IDEA it looks like the following:



You can simply double-click the jetty:run option to deploy the app and start the Jetty server, or you can right-click the option to create a running configuration that will be shown on the top of the IDE's window. This last method has the advantage of offering a keyboard shortcut for the running configuration as well.
You can alternatively use any other server that includes a Web Servlet to deploy and run the application. For example Tomcat or GlassFish. We won't cover this topic here. There are plenty of useful resources on the web that explains how to use these servers.

Once the app is compiled, point your browser to http://localhost:8080 to see the result. Keep in mind that the compilation may take some time the first time you are doing it since you might not have all the Maven dependencies in your hard drive, but this is going to be much faster afterward, for both this project and new ones as well. Here's a screenshot of the application:

Add behavior to the web application

Vaadin includes many ready-to-use UI components. There are buttons, combo boxes, grids, check boxes, text fields, charts, and many others. Let's use the TextField and Button classes to add some interactivity to the web application.

Start by creating instances of these two classes in the constructor:

TextField textField = new TextField("What's your name?");
Button button = new Button("Ok");

We want to show a personalized greeting containing the name introduced in the text field anytime the user clicks the button. The way you react to user actions (like clicking a button) is by adding listeners. In the case of a Button, a click listener:

button.addClickListener(e -> ... your custom code here ...);

Let's use yet another Vaadin UI component to show a message: Notification:

button.addClickListener(e -> Notification.show("Hello"));

The greeting is not personalized yet. We want to use the name introduced in the text field as part of the greeting. We can get this value by using the TextField.getValue() method. Cannot be easier:

button.addClickListener(e -> Notification.show("Hello " + textField.getValue()));

There, you have new components and behavior in your app. We are just missing one last thing–we created and configured UI components, but we never added them into the VerticalLayout. Use the add method to fix this:

add(textField, button);

Restart the Jetty server and go to http://localhost:8080 to see the changes:

What next?

There are many other cool features in Vaadin. I would suggest you continue with the official Vaadin Tutorial at https://vaadin.com/tutorials/getting-started-with-flow which explains how to build a more real-life application. If you want to master Vaadin, I suggest reading the documentation at https://vaadin.com/docs.
Share:

Tuesday, July 3, 2018

Data-Centric Applications with Vaadin 10?

I recently got some hard copies of my last book about Vaadin. I love the matte colored look of the cover. Excellent job by Packt Publishing! Anyway, since the feeling of receiving a package with your own books is hard to describe with words, I decided to do it with code.

Although most of the concepts and design ideas that the book covers are valid for any version of Vaadin, I created a Git branch with all the examples migrated to Vaadin 10. At this time, there are certain features that Vaadin 10 doesn't include (yet?) such as Grid editors, Menus, and LAYOUT_COMPONENT_GROUP styles. But besides that, pretty much everything was easy to migrate.

There are some new features in Vaadin 10 that, obviously, I didn't cover in the book–things such as the new Router and the Element API. However, since the book is aimed at developers with basic Vaadin knowledge (i.e., they how to code UIs with the Vaadin Java API), the examples are useful and illustrate techniques you can use in your applications: modularization, authentication, authorization, database connectivity (with JDB, JPA, MyBatis, and jOOQ), CRUD user interfaces design, lazy loading, and reporting with JasperReports.

Keep in mind that this book is not for total beginners. If you don't know what kind of components are available in Vaadin and how to use the basic functionality they provide, you should start with the introduction to Vaadin Flow and the official Vaadin tutorial.
Share:

Friday, May 4, 2018

What's so cool about Vaadin Flow?

Vaadin Flow is a free open-source web framework for Java developers. It allows you to implement a web application without having to code any JavaScript or HTML. See the following example:

@Route("")
public class MainView extends VerticalLayout {
    public MainView() {
        TextField textField = new TextField("Enter your name");
        Button button = new Button("Click me", event ->
                add(new Label("Hello from the server, " + textField.getValue())));
        add(textField, button);
    }
}

​If you deploy this to a Java server, you'll get the following:



Since the UI code runs on the server side, you can debug it using the tools that your Java IDE of your choice provides. For example, here we are adding a breakpoint in the line that gets invoked when the button is clicked:



These are some of the cool things about Vaadin Flow:

  • You can use one single programming language to implement a web application (Java or any other for the JVM).
  • ​You can “connect” Java business logic easily–just call the Java method, no need to implement REST web services and parse JSON.
  • You can “forget” about certain security issues. For example, if a button is disabled and a malicious user enabled it with for example Chrome DevTools in the browser and clicked it, the framework wouldn’t call the server-side listener anyway–if a button is disabled, you can rest assured the server logic won’t be invoked.
  • Flat learning curve. Since the programming model is closer to desktop development, developers can start maintaining applications easily.
  • Vaadin Flow includes many ready-to-use components such as ComboBox, DatePicker, Grid, Dialog, Checkbox, ProgressBar, Notification, Tabs, and many others.
  • You can create your own UI components by using object-oriented composition, HTML, and JavaScript.
  • It makes it easy to integrate existing Web Components. So, if you find or develop a useful Web Component, you can wrap it in a server-side Java class.
  • You can manipulate the DOM from the server side. You have full access to the underlying DOM in the browser form the server.

There are more cool features in Vaadin Flow. The following videos show some of them in action:

Share:

Monday, April 23, 2018

New book about Vaadin 8: Data-Centric Applications with Vaadin 8

I'm glad to announce that my second book about Vaadin has been published!

Due to Packt Publishing's guidelines, the space I had for acknowledgments was limited to 500 characters. However, I'd like to share the original draft I wrote for this section:

​I'd like to thank the entire team from Packt Publishing; thanks for your support and patience throughout the writing process. Thanks to all the technical reviewers and proofreaders for providing me with valuable feedback from which I have learned a lot. A special thanks to the Vaadin team and its community for producing a terrific open-source web framework and knowledge base with tons of articles and useful resources. I hope this book reciprocally contributes back to the community.

I'd like to single out Joonas Lehtinen, Sami Ekblad, Matti Tahvonen, Marcus Hellberg, and Fredrik Rönnlund, who in one way or another influenced or motivated this book. In addition, many others provided help and motivation throughout the writing process. Specifically, and in no particular order, I'd like to thank Nicole Mattsson, Jet Dario, Noomi Ylä-Lahti, Dora Quintero, Saara Nevala, Marcelo Duarte, Guillermo Alvarez, Goran Atanasovski, Johannes Häyry, Anna Emelyanova, Kari Söderholm, Paul Römer, Ville Ingman, Amahdy Abdelaziz, Sven Ruppert, Eero Mäkelä, Artem Godin, Jan Rucidlo, Julia Toivonen, Ömer Tümer, Binh Bui, Mikko Inkinen, Shridhar Deshmukh, Frederik Raulf, and all my colleagues at Vaadin Ltd.

Thanks to my parents and siblings for being supportive and helpful throughout my life; I genuinely enjoyed writing part of this book with your company. As Shakespeare wrote in King Lear, in this list you are "although the last, not least".
Share:

Wednesday, March 28, 2018

Microservices & Vaadin

During the last months, I've been researching and experimenting with microservices and Vaadin applications. My goal was to test Vaadin "compatibility" with some of the techniques associated with microservices. In short, Vaadin is as compatible with microservices as any other component-based web framework. Moreover, many of the challenges you would face when implementing microservices with Vaadin you would face with any JavaScript/HTML framework.

Microservices bring advantages such as independent development and deployment of services, but they come with a cost, mainly, an increase in complexity, brilliantly explained by Dave Kerr in his article The Death of Microservice Madness in 2018, a highly recommended read for everyone evaluating microservices. One of the key technical challenges with microservices which is related to web frameworks is how to create a "mash-up" UI that combines two or more web applications.

Ignoring the fact that microservices embrace technology independence to some extent (that is, teams can decide which technologies to use, including web frameworks), I was interested in how to render two independently deployed Vaadin applications into one single page in the browser. It turned out, again, the challenges I faced were almost the same I would have faced with any other web framework, especially, dealing with CSS and JavaScript collisions and HTTP session management.

I was able to develop an application using Spring Boot with Spring Cloud to show a web page with a CRUD UI on the left and a Twitter feed on the right, both developed with Vaadin:

Running this application requires starting at least 7 processes, 3 orchestration services, 1 back-end service, and 3 web applications:


You can find detailed information about my experiment in this series of articles:

  1. Getting Started with Microservices
  2. Microservices: Service Registration and Discovery
  3. Microservices: Externalized Configuration
  4. Microservices: Consuming stateless services from Vaadin UIs
  5. Microservices: Fault Tolerance
  6. Microservices: UI composition
  7. Microservices: High availability
  8. Microservices: Health monitoring
Share:

Tuesday, March 27, 2018

New book about Vaadin Framework 8 coming out

As some of you may already know, I started writing a book about Vaadin 8 for Packt Publishing almost a year ago. After inevitable hindrances and changes in the scope and schedule, the book is almost ready now!

The book is addressed to Java web developers with basic knowledge of the Vaadin Framework 8. If you have followed the tutorial at https://vaadin.com/docs/v8/framework/tutorial.html and have played around with the framework, this book is for you. Of course, more experienced developers can also find interesting ideas in this book.

The book covers topics related to software design such as code organization, modularization, and API design. It also serves as a practical guide to common features in business applications, ranging from authentication and authorization to reporting and CRUD user interfaces.

Here's the outline (chapters) of the book:

  1. Creating new Vaadin projects
  2. Modularization and main screens
  3. Implementing server-side components with internationalization
  4. Implementing authentication and authorization
  5. Connecting to SQL databases
  6. Implementing CRUD user interfaces
  7. Adding reporting capabilities
  8. Lazy loading

​I'll announce on Twitter and here once the book gets published. Stay tuned!
Share:

Friday, December 2, 2016

Enterprise-app for Vaadin

Some years ago I published the Enterprise-app add-on for Vaadin. The most awarded feature was the CrudComponent class that allowed you could add a CRUD-like interface to any Hibernate entity by writing one line of code. Enterprise-app was (and still is) available for Vaadin 6. I partially migrated it to Vaadin 7, but never really completed the task.

I'm not longer supporting the Enterprise-app add-on, but working in a set of new Vaadin add-ons to replace parts of its functionality. So far I have implemented the Crud UI add-on, with a less magical but much more flexible CrudComponent. A key difference with the old one is that it doesn't perform the actual CRUD operations, instead, it delegates the operations to a CrudListener with 4 methods that you have to implement (or alternatively, use 4 separte interfaces and lambda expressions or method references). This allows you to use any persistence technology you want.

Suppose you have a JavaBean like the following:

public class User {
    private Long id;
    private String name;
    private Date birthDate;
    private String email;
    private String password;
    
    ... getters & setters ...
}

And a "backend" service class like the following:

public class Backend {
    Collection<User> findAll() { ... }
    User add(User user) { ... }
    User update(User user) { ... }
    void delete(User user) { ... }
}

Then, with the Crud UI add-on, you can create a CRUD web interface with the following code:

GridBasedCrudComponent<User> crud = new GridBasedCrudComponent<>(User.class);
crud.setFindAllOperation(() -> backend.findAll());
crud.setAddOperation(backend::add);
crud.setUpdateOperation(backend::update);
crud.setDeleteOperation(backend::delete);

There are several configuration options. See the examples on the add-on's page. The following is an example of a CrudComponent with modified configuration settings for Grid's columns, field captions, layout, and validations:

If you were a user of Enterprise-app, take a look at the new Crud UI add-on and let me know any issues you find or features you would like to have.

Happy coding!
Share:

Wednesday, June 8, 2016

Vaadin Video Tutorials

Finally! After endless hours of rehearsal, screen recording, audio recording, film recording, audio-image synchronisation, editing work, and do it all over again, we have published the first 6 videos of the Vaadin Tutorial series. But don't get me wrong, working on these videos was a lot of fun and I'm looking forward to publish more video content.

Share:

Friday, June 13, 2014

Talking Progress Indicators

Willing to learn Vaadin 7 in a funny way? Here there is an excerpt of my book Vaadin 7 UI Design by Example: Beginner's Guide.
Author: Let me introduce you to a friend. ProgressIndicator, reader. Reader,
ProgressIndicator. 
Author: Now that you know each other, let's work together.

ProgressIndicator: Cool, what's the task to do?

Author: Well, our awesome algorithm is taking too long and users are just leaving our state-of-the-art web application. So ProgressIndicator, we need your help to give
the user some feedback about the progress of the process.

ProgressIndicator: Sure.

Author: Thank you sir. Take a look at our original application implementing this Java Thread performing our high-tech algorithm: 
 public class ProgressindicatorUI extends UI {

  private class HighTechAlgorithm extends Thread {
    public void run() {
      try {

        for (int i = 0; i < 10; i++) {
          sleep(1000);
        }

      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
  }

  protected void init(VaadinRequest request) {
    final VerticalLayout layout = new VerticalLayout();
    layout.setMargin(true);
    setContent(layout);

    Button button = new Button("Start awesome algorithm");

    button.addClickListener(new Button.ClickListener() {
      public void buttonClick(ClickEvent event) {
        new HighTechAlgorithm().start();
      }
    });

    layout.addComponent(button);
  }

} 
ProgressIndicator: Wow! That's an awesome algorithm.

Author: Thank you. It took us months to implement it. Anyways, we would like to add you, Mr. ProgressIndicator, to our layout, so you can tell the user how the progress of the algorithm is going. Is that OK for you?

ProgressIndicator: Sure. Let me place myself as a private member of your UI class.

Author: Of course, come in. And please add yourself into our main layout: 
 public class ProgressindicatorUI extends UI {

  private ProgressIndicator mrProgressIndicator =
      new ProgressIndicator();

  // ...

  protected void init(VaadinRequest request) {

    // ...

    layout.addComponent(mrProgressIndicator);
  }
} 
ProgressIndicator: What a nice place. Really high-tech. 

Author: Yeah, we painted it Vaadin color.

ProgressIndicator: My favorite color!

Author: Nice. For each iteration of our algorithm I will update you, OK?

ProgressIndicator: Yes please.

Author: Cool. You accept values in which range?

ProgressIndicator: Give me a float between 0 and 1.

Author: OK. There you go: 
 public class ProgressindicatorUI extends UI {

  // ...

  private class HighTechAlgorithm extends Thread {

    public void run() {
      try {

        for (int i = 1; i <= 10; i++) {
          sleep(1000);
          mrProgressIndicator.setValue(i * 0.1f);
        }

      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }

  }
} 
ProgressIndicator: Thank you. I think I'm ready.

Author: Great! Let's run the app. Are you ready reader? You have been kind of quiet lately.

ProgressIndicator: Yeah. I think she/he might be overwhelmed by the high-tech algorithm.

Author: That's reasonable. Let's test our application: 

ProgressIndicator: Cool. I'm working properly!

Author: Wonderful job ProgressIndicator. Thank you very much.

ProgressIndicator: My pleasure.
Share:

Thursday, September 19, 2013

Book Give-away: Hold a chance to win free copy of the book "Vaadin 7 UI Design By Example", just by commenting!

And the winners are:
  • Iskael Diaz Marquez
  • Camilo Gonzalez
Packt Publishing has two copies of Vaadin 7 UI Design By Example to be given away to two lucky winners.

How you can win:
To win your copy of this book, all you need to do is come up with a comment below highlighting the reason why you would like to win this book.

Please note: Winners residing only in the USA and Europe would get a chance to win print copies. Others would be provided with eBook copies only.

Duration of the contest & selection of winners:
The contest is valid up until October 5th 7th 12th, and is open to everyone. Winners will be selected on the basis of their comment posted. 
About the book:

This is what Packt Publishing says about the book:Vaadin 7 UI Design By Example written by Alejandro Duarte, is an engaging guide that teaches the user how to develop web applications in minutes. This book shows the user how to use Eclipse, Netbeans, and Maven to create Vaadin projects. It then demonstrates how to use labels, text fields, buttons, and other input components. The book also explains Vaadin theory to prepare the user for the rest of the trip that will enhance their knowledge of Vaadin UI components and customization techniques.

Join the contest! Leave your comment!
English, Spanish, Italian, Russian, any language accepted!
Please note that comments are moderated and your comment will not appear immediately.
Share:

Friday, February 22, 2013

Enterprise App now available with Maven


Finally! I've managed to write a Maven POM for Enterprise App. Just add this into your pom.xml file:

<dependency>
    <groupId>org.vaadin.addons</groupId>
    <artifactId>enterprise-app</artifactId>
    <version>0.4.0</version>
</dependency>

You might need to add the official Maven repository for Vaadin addons as well:

<repository>
    <id>vaadin-addons</id>
    <url>http://maven.vaadin.com/vaadin-addons</url>
</repository>

Better late than never ;)

Share: