Pular para o conteúdo principal

Fetching REST Data Sources with DataFX

DataFX is a project that helps you to show data in a JavaFX application from different sources of data in a few formats. You may read local data using the FileSource and this datasource may contain data in XML or CSV formats. I demonstrated how to use it in a previous post, today I want to quickly show you show to fetch data using the new RestRequestBuilder class.

RestRequestBuilder is very easy to use and with a few lines of code you will be able to fetch a JavaFX TableView from a remote XML, JSON or CSV source. As the name says, this class uses the builder way to create REST requests, which means that in a simple line of code you will have your request ready to fetch data in a TableView. Then you will simply have to inform to your datasource(as datasource you can understand a XMLDataSource or CSVDatasource).

Well, this post is very abstract so far, is time to use what we talked about in a program. To do that I want to present you a WEB Service I created a few years ago that allows to access information of our Brazilian Election Candidates using REST. The advantages of it is a centralized, "machine ready" and aggregated base of data, so will have one place to access using programatic ways and it will allow you to create Mashups and other applications (we need to be careful with politics in Brazil, we have a lot of corrupt politcs here :-(). The API is very simple to use and it was published in ProgrammableWeb, which is a site that has as objective put together all APIs(SOAP, REST or Javascript) and Mashups made with these APIs.

The main method of the API is the search. With three query parameters we can query all the base of data and bring the data in XML or JSON format. For example, the URI:

http://williamprogrammer.com/EleicoesAbertas/apiEleicoes/beta/2010/candidatos/busca?nome=ANT
Will bring all the candidates that has "ANT" in the name. The default format of the data offered by the API is XML. Additionally you can inform the page you are reading by using the parameter "pagina", but it's out of scope of this post. We will consume this source of data in JavaFX.

Now we know the target service to consume, we need to know how DataFX will help us to show these data. First, we can use RestRequestBuilder as follow:

NetworkSource ns = new RestRequestBuilder(
    "http://williamprogrammer.com")
    .path("EleicoesAbertas/apiEleicoes/beta/2010/candidatos/busca")
    .queryParam("nome", "ANT").build();
As the data is served in XML format, we need to chose which columns we will show in the TableView(I chose "nome", "nomeUrna", "estadoCivil", "resultadoEleicao", and "sexo") and the root element that contain the content to this columns(in our case it is "candidato"). The following code shows how can we retrieve this information.
XMLDataSource candidatosDataSource = new XMLDataSource(
    ns, "candidato", "nome", "nomeUrna",  "estadoCivil",
    "resultadoEleicao", "sexo");
By last we need to fill our TableView. It's pretty straightforward and described in my previous post. To finish here is our entire code and an image of the resulting JavaFX app.

package view;

import javafx.application.Application;
import javafx.scene.SceneBuilder;
import javafx.scene.control.TableView;
import javafx.stage.Stage;

import org.javafxdata.datasources.io.NetworkSource;
import org.javafxdata.datasources.io.RestRequestBuilder;
import org.javafxdata.datasources.protocol.XMLDataSource;

/**
 * 
 * @author jesuino
 * 
 */
public class Main extends Application {

 @SuppressWarnings("unchecked")
 @Override
 public void start(Stage stage) throws Exception {
  stage.setTitle("DataFX Test");
  // Just loading the URL and creating a Networkdatasource for it
  NetworkSource ns = new RestRequestBuilder(
    "http://williamprogrammer.com")
    .path("EleicoesAbertas/apiEleicoes/beta/2010/candidatos/busca")
    .queryParam("nome", "ANT").build();

  ns.setAccept("application/xml");
  XMLDataSource candidatosDataSource = new XMLDataSource(
    ns, "candidato", "nome", "nomeUrna", "estadoCivil",
    "resultadoEleicao", "sexo");
  @SuppressWarnings("rawtypes")
  TableView candidatos = new TableView();

  candidatos.getColumns().addAll(
    candidatosDataSource.getNamedColumn("nome"),
    candidatosDataSource.getNamedColumn("nomeUrna"),
    candidatosDataSource.getNamedColumn("estadoCivil"),
    candidatosDataSource.getNamedColumn("resultadoEleicao"),
    candidatosDataSource.getNamedColumn("sexo"));
  candidatos.setItems(candidatosDataSource);
  stage.setScene(SceneBuilder.create().root(candidatos).build());
  stage.show();
 }

 public static void main(String[] args) {
  Application.launch(args);
 }
}

AS you can see it's very easy to read a remote REST Datasource with DataFX and it will get better since it's an open source project. Of course you can use it in a more complex application, it's a simple demonstration.

Comentários

  1. Muito bom! Só falta você colocar em português p/ galera que tem um pouco de dificuldade com o idioma...

    ResponderExcluir

Postar um comentário

Postagens mais visitadas deste blog

Creating custom Work Item Handler in BPM Suite/jBPM 6

Hi all! In this post I am going to share my experience creating a work item handler for BPM Suite 6.0.3 (which is very similar to jbpm as explained in a previous post ). The Hello World Work Item Handler Let's create a really simple WorkItemHandler just to print "Hello World" in the console. Of course you can implement more feature and make it receive parameters, access database, web services, etc. But in this post we will keep it simple. Really simple. First thing to do is to create a maven project for my WorkItemHandler. Here's the pom.xml of my Maven project: Notice that we are importing jbpm dependency so we can find the java interface that is used to create work item handlers. Now we can start coding. Let's create a class name HelloWorkItemHandler in package org.jugvale.jbpm, here is the simple code: Now we can build our project and go to BPM Suite to configure it so we can use this workitem. Registering the WorkItemHandler UPDATE...

Using the REST Task from jBPM 6

In this post I am going to share my experience using the BPM Suite 6 REST Task. BPM Suite  X jBPM jBPM is a JBoss community project to offer an open source and efficient BPM Suite and BPM Suite is a product created by Red Hat based on jBPM. In this post I will be using BPM Suite because I have it installed already, but what I am going to described should work for jBPM as well.   REST Task  The REST Task is used to invoke a REST resource (or perform an HTTP Request) from your Business Process. You can set the URL, HTTP Method, timeout and credentials from the Process Modeller interface and when the process gets into that task, it will generate a HTTP Request and return the response as String. It is available on the left side pallet under the "Service Tasks" tab: The Target REST Web Service The service we are going to access from our process is a really simple one, that's why it is called simple-hello-rs and it is based on JBoss helloworld-rs qu...

Simplest JavaFX ComboBox autocomplete

Based on this Brazilian community post , I've created a sample Combobox auto complete. What it basically does is: When user type with the combobox selected, it will work on a temporary string to store the typed text; Each key typed leads to the combobox to be showed and updated If backspace is type, we update the filter Each key typed shows the combo box items, when the combobox is hidden, the filter is cleaned and the tooltip is hidden:   The class code and a sample application is below. I also added the source to my personal github , sent me PR to improve it and there are a lot of things to improve, like space and accents support.