Posts on this Category



AngularJS Tutorial: Consuming Java EE Web Services

It’s very common to see people asking how to integrate Java EE applications with some of the popular JavaScript frameworks, specially with AngularJS. In most cases developers already have an application (or a great portion of it) written in Java EE containing all the business logic, and since it’s not feasible to rewrite everything in JavaScript, they look for ways to integrate and add new technology to the project without losing any existing code.

That’s when Web Services comes in handy!! They allow your AngularJS application to send and receive data from the Java EE module in a very easy way. Of course there are more sophisticated ways to do this communication, but that is a subject for another post.

The first step is to expose the Web Service in your Java EE project, I’m assuming that you already have this project ready, but if you don’t, just create one by following the instructions in this link.

Now that you already have your web service, make sure it’s working before you continue, to do that, open your browser and call your service by typing it’s URL, it should follow this pattern:

1
2
3
{domain}:{port}/{projectName}/{webServicePath}
 
//example: http://localhost:8080/WebServiceEJB-war/test

If everything is right the browser will display the data returned by your web service, if it doesn’t you’re probably missing something, make sure you followed every instruction in the example I mentioned above.

Now we can start writing some AngularJS code, after setting up the project let’s create the app.js file like this:

1
2
3
4
5
6
7
var app = angular.module('angularWS',[]);
app.controller('myController', function($scope, $http){
	$http.get('http://localhost:8080/WebServiceEJB-war/test')
		.success(function(data){
			$scope.text = data;		
		});	
});

This is the simplest way to consume a web service with angular, the $http.get function will make the request to the Java EE application, all you need to do is to pass the web service URL, when it receives the data, it will execute the callback passed to the success() function, there you can do anything you want with the data, in my case I’m just assigning it to the $scope.text variable. When your Angular application make the request, it’ll probably get an Cross-Origin Request Blocked error, in this case just follow the steps in this link to fix it.

ReactJS DataTable with Sort, Filter and Pagination Example (PART 1)

fixed-data-table home page
fixed-data-table home page

Today we’re going to learn how to create a simple datatable for react using the FixedDataTable module, since it uses Javascript ES6 code you must have at least some basic knowledge about it. To c ompile our ES6 code we’re going to use Babel and Webpack, since our js files will also contain JSX and React code, besides babel-preset-es2015 we are going to need babel-preset-react as well.

So let’s get started, create your project folder and run npm init to create the package.json file, after that we need to add all the dependencies, the following code has everything we need, just copy and paste it in there:

package.json

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
{
  "name": "test",
  "version": "1.0.0",
  "description": "",
  "main": "main.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "babel-core": "^6.3.17",
    "babel-loader": "^6.2.0",
    "babel-preset-es2015": "^6.3.13",
    "babel-preset-react": "^6.3.13",
    "babel-runtime": "^6.3.19",
    "webpack": "^1.12.9"
  },
  "dependencies": {
    "fixed-data-table": "^0.6.0",
    "react": "^0.14.3",
    "react-dom": "^0.14.3"
  }
}

As devDependencies(dependencies we need only for development) we have webpack and some babel modules, and as regular dependencies we’ll only need react and the fixed-data-table module. Now run npm install, it’ll download and install all the dependencies, it may take a while.

The next step is to configure the webpack module, to do that we need to create the webpack.config.js file and add the following code to it:

webpack.config.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
"use strict";
 
module.exports = {
  entry: './main.js',
  output: { path: __dirname, filename: 'bundle.js' },
 
  module: {
    loaders: [
      {
        test: /.js?$/,
        loader: 'babel-loader',
        exclude: /node_modules/,
        query: {
          presets: ['es2015', 'react']
        }
      }
    ]
  },
};

In this file I’m just specifying the files webpack should transform (or transpile) and what loaders it should use to do it. As the entry file we have the main.js, and as the output (the transformed file) we have the bundle.js, both files were not created yet. We’re also saying to webpack that babel-loader will be our loader and that it should test and transform every js file in our project, except the ones inside the node_modules folder. Lastly we are defining es2015 and react as our presets.

OK, now we’re ready to write some code, first let’s create the main.js file with the following code:

main.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import React from 'react';
import ReactDOM from 'react-dom';
import {Table, Column, Cell} from 'fixed-data-table';
 
const rows = [{"id":1,"first_name":"William","last_name":"Elliott","email":"welliott0@wisc.edu",
"country":"Argentina","ip_address":"247.180.226.89"},
{"id":2,"first_name":"Carl","last_name":"Ross","email":"cross1@mlb.com",
"country":"South Africa","ip_address":"27.146.70.36"},
{"id":3,"first_name":"Jeremy","last_name":"Scott","email":"jscott2@cbsnews.com",
"country":"Colombia","ip_address":"103.52.74.225"},
 
// more data
];
 
ReactDOM.render(
    <Table
      height={rows.length * 30}
      width={1150}
      rowsCount={rows.length}
      rowHeight={30}
      headerHeight={30}
      rowGetter={function(rowIndex) {return rows[rowIndex]; }}>
 
      <Column dataKey="id" width={50} label="Id" />
      <Column dataKey="first_name" width={200} label="First Name" />
      <Column  dataKey="last_name" width={200} label="Last Name" />
      <Column  dataKey="email" width={400} label="e-mail" />
      <Column  dataKey="country" width={300} label="Country" />
 
    </Table>,
    document.getElementById('example')
);

This code can already gerenate a basic datatable, but without any features yet (sort, filter and pagination). As you can see I’ve used some JSON data to populate the datatable, but feel free to use your own data if you want. Now if you take a look at the code of our actual table component you’ll see that it’s really easy to understand, almost every attribute of the Table tag is responsible for controlling its dimensions, except the rowGetter, which is responsible for saying where each row should get its data. We should focus on the Column tags, which by far are also very simple, besides the attribute width, we have the dataKey and label, the first one is the name of the JSON field that will be displayed in this column, and the second is the text that will appear in the header.

Now let’s create our HTML:

index.html

1
2
3
4
5
6
7
8
9
10
11
12
13
<!doctype html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>React DataTable</title>
    <link href="node_modules/fixed-data-table/dist/fixed-data-table.css" 
          rel="stylesheet">
  </head>
  <body style="font-family:arial;font-size:12px; background:#e1e1e1">
    <div id="example"></div>
    <script src="bundle.js"></script>
  </body>
</html>

This is just a regular html file, I just added the css from the fixed-data-table module and also the bundle.js, which is the compiled version of our main.js, it’s really important that you put the bundle.js at the end of the body, otherwise it won’t be able to render the datatable.

Now just run the command webpack to generate the bundle.js, if everything goes right you can now open your index.html file on your browser, this should be the result:

ReactJS datatable
ReactJS datatable

Perfect!! Now our datatable can already show the data in the browser, the next step is to start adding some features to this table, like pagination, sorting and filtering, but I’ll leave that to the PART 2 of this tutorial.

That’s it for today!! hope you enjoyed, till the next one!!

How to use ES6 (Very Simple Example)

Compiling Javascript ES6 Code with Babel
Compiling Javascript ES6 Code with Babel

This will be a very simple tutorial on how to use, the new and far more sophisticated version of Javascript, the ES6 (or ES2015 if you prefer). Much people say ES6 is the future of Javascript, but as everybody knows, our browsers cannot run code in this format yet. Web developers are already writing Javascript in ES6 format and using transpilers to transform it into ES5 code so the browsers can read it. For those who doesn’t know, a transpiler is kind of a compiler that converts a code written in one programming language to another similar programming language, in our case from ES6 to ES5.

The reason why I decided to make it simple is because I’ve already seen lots of authors writing more complex and long tutorials involving Grunt, Browserify, JSX, and so on. You would probably spend a reasonable amount of time going through these tutorials. As opposed to them, my goal here is to get you writing ES6 code as quickly as possible, without consuming much of your time.

So let’s get started, the first thing we need is a transpiler, for this tutorial I’m going to be using Babel, to install it just run the following command:

1
npm install babel-cli -g

Now, since Babel doesn’t come with any transformations enabled, we need to explicitly tell what kind of transformation to perform, to do that we also have to install ES2015 preset:

1
npm install babel-preset-es2015 -g

Perfect! Now we’re going to need to write some ES6 code to test if Babel is working, copy the following code into a js file:

test.js

1
2
3
4
5
6
7
8
9
10
11
12
13
class MyFirstES6Class {
  constructor(message) {
    this._message = message;
  }
 
  get message() {
    return this.message;
  }
 
}
 
var myClass = new MyFirstES6Class('Hello World!!');
console.log(myClass.message);

Ok, now via terminal just navigate to your folder and run the following command to generate the compiled js:

1
babel --presets es2015 test.js --out-file compiled.js

That’s it!! If you did it right you should now have the compiled.js file containing the transformed code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { 
throw new TypeError("Cannot call a class as a function"); } }
 
var MyFirstES6Class = (function () {
  function MyFirstES6Class(message) {
    _classCallCheck(this, MyFirstES6Class);
 
    this._message = message;
  }
 
  _createClass(MyFirstES6Class, [{
    key: 'message',
    get: function get() {
      return this.message;
    }
  }]);
 
  return MyFirstES6Class;
})();
 
var myClass = new MyFirstES6Class('Hello World!!');
console.log(myClass.message);

Compiling JSX ReactJS code with Browserify and Reactify

This will be a very basic tutorial for those who are just getting to know React, by now you should have noticed that React uses JSX code, which is basically Javascript with some HTML elements. The problem here is that the browser cannot understand JSX, if you have already tried it you probably saw something like this on your firebug:

SyntaxError: expected expression, got ‘<'

In order to make it possible for the browser to interpret it we have convert the JSX into regular Javascript code, to achieve that we need to use tools like Browserify and Reactify.

Browserify, is a tool that let’s you use the function require(‘module’) in the front-end exactly like you do in the back-end with Node.js, then it compiles everything and generates a single JS file which will be referenced on your page. Reactify is pretty much the same thing, but it supports JSX code, Browserify alone wouldn’t be able to compile it.

Let’s take a look at an example, the first thing you need to do is to install both browserify and reactify:

1
2
3
4
5
//INSTALLS BROWSERIFY
npm install browserify
 
//INSTALLS REACTIFY
npm install reactify

Now, you probably have in you project a JSX file like this one (in my case it’s on the ‘src’ folder):

app.jsx

1
2
3
4
5
6
7
8
9
var ReactDOM = require('react-dom');
var React = require('react');
 
var HelloWorld = React.createClass({
 render: function() {
   return <div>Hello World!!</div>;
 }
});
ReactDOM.render(<HelloWorld />, document.getElementById('component'));

What you need to do now is to transform this into a JS file so the browser can read it, already with browserify and reactify installed just navigate to your project folder and type the following command:

1
browserify -t reactify src/app.jsx -o build/app.js

Perfect!! Now you have the app.js file in your ‘build’ folder, you can now use it in your HTML page like this:

1
2
3
4
5
6
7
8
9
10
11
<!DOCTYPE html>
<html>
   <head>
	   <title>React DataTable</title>
	   <script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
   </head>
   <body>
	   <div id="component"></div>
	   <script src="build/app.js"></script>
   </body>
</html>

That’s it!! Hope I helped you with this tutorial, till the next one!!

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource (Reason: CORS header ‘Access-Control-Allow-Origin’ missing)

This is a very common error for people who are just getting started with Web Services, it’s really simple to solve but sometimes developers spend hours struggling to find a solution. It happens when you create a web service and tries to access it from a different application, it won’t work because you don’t have Cross-origin resource sharing (CORS) enabled, which means an application loaded in one domain cannot interact with resources from a different domain. All you have to do is to enable CORS.

How you can active it will depending on your scenario, in this tutorial I’m going to show how to enable CORS for a Java EE application running on Glassfish, I’m assuming you have an EJB RESTful web service similar to this one, and when other applications tries to consume it you see the Cross-Origin Request Blocked error on your firebug console, in this case all you have to do is to create a filter in your application, just create a class exactly like this one on your project:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
 
public class CORSFilter implements Filter {
 
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }
 
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, 
            FilterChain filterChain) throws IOException, ServletException {
        final HttpServletResponse response = (HttpServletResponse) servletResponse;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, HEAD, OPTIONS");
        response.setHeader("Access-Control-Allow-Headers", "Origin, Accept, x-auth-token, "
                + "Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers");
        filterChain.doFilter(servletRequest, servletResponse);
    }
 
    @Override
    public void destroy() {
 
    }
 
}

Now you have to register the filter in your web.xml, copy the following code and replace “yourPackage” with your actual package name:

1
2
3
4
5
6
7
8
<filter>
    <filter-name>cors</filter-name>
    <filter-class>yourPackage.CORSFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>cors</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

That’s it! Now your application will allow its resources to be shared with other domains.

React.js Tutorial: Consuming JavaEE RESTful Web Services

In this post I’m going to show how to consume Web Services with React.js, more specificalyJavaEE RESTful Web Services. I’ve already written a post showing how to create these web services with EJB 3, if you haven’t seen it yet just click on this link for more details, but if you’re already familiar with Java EE feel free to skip it and create your owm web service.

For this tutorial I’m going to use the following service (Which is almost the same as I created on the other post):

1
2
3
4
5
6
7
8
9
10
11
@Stateless
@Path("/test")
public class WebServiceTest {
 
    @GET
    @Produces("text/plain")
    public String test() {
        return "Web Service Test";
    }
 
}

This is as simple as it gets, just a method returning a string, simple as that! If you deploy the project you’ll be able to see the text “Web Service Test” on your browser by adding /test to the end of your URL:

Java EE REST Web Service Example
Java EE REST Web Service Example

Now let’s create the React.js project to consume this web service. Again, I already have a post about how to get started with React.js, click on the link to see it, though it doesn’t say anything about how to consume web services it can still be useful for those who are not familiar with react.

Since my goal here is to just show how to consume a web service, I’ll keep the react code very simple as well, just copy the following code into your index.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<!DOCTYPE html>
<html>
    <head>
        <title>React Flux</title>
        <script src="https://fb.me/react-0.13.3.js"></script>
        <script src="https://fb.me/JSXTransformer-0.13.3.js"></script>
        <script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
    </head>
    <body>
        <div id="component"></div>
 
        <script type="text/jsx">
            var JavaEEWSTest = React.createClass({
                getInitialState: function () {
                    return {text: ''};
                },
                componentDidMount: function(){
                    $.ajax({
                        url: "http://localhost:8080/WebServiceEJB-war/test"
                    }).then(function(data) {
                        this.setState({text: data});
                    }).bind(this)
                },
                render: function() {
                    return <div>Response - {this.state.text}</div>;
                }
            });
 
            React.render(<JavaEEWSTest />, document.getElementById('component'));
 
        </script>
    </body>
</html>

As you can see I have 3 functions here: getInitialState, componentDidMount and render. They do exactly what their names sugest, the first one sets all the initial values, the second executes when the component is mounted, and the last one is responsible for rendering the component. The most important for us is the componentDidMount, that’s where the web service is called, and after it receives the response it will be assigned to the variable ‘text’.

We’re almost done, now if you execute it you will probably see the following error (you need firebug installed):

Cross-Origin Request Blocke
Cross-Origin Request Blocke

To see more details about this error click here, to solve it just add the following filter to your Java EE project:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
 
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
 
public class CORSFilter implements Filter {
 
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }
 
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, 
            FilterChain filterChain) throws IOException, ServletException {
        final HttpServletResponse response = (HttpServletResponse) servletResponse;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, HEAD, OPTIONS");
        response.setHeader("Access-Control-Allow-Headers", "Origin, Accept, x-auth-token, "
                + "Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers");
        filterChain.doFilter(servletRequest, servletResponse);
    }
 
    @Override
    public void destroy() {
 
    }
 
}

And in the web.xml:

1
2
3
4
5
6
7
8
<filter>
    <filter-name>cors</filter-name>
    <filter-class>yourPackage.CORSFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>cors</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

Perfect!! Now if you refresh the page this will be the result:

Simple React.js application getting data from Java EE REST Web Service
Simple React.js application getting data from Java EE REST Web Service

It’s really simple, but the string ‘Web Service Test’ is coming from our web service.

Hope this tutorial was helpful for you, till next time!

Tutorial: ng-table with infinite scroll

I’ve already showed in this blog how to create a basic datatable with ng-table, for those who didn’t see it yet, just click on the link. This tutorial will just be a complement to the previous one, the difference is that instead of using pagination I’m going to use infinite scroll, and don’t worry, I’ll also keep the sorting and filtering features.

So before we start let’s just put the links to every script we need, your index.html should look like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<!DOCTYPE html>
<html ng-app="ngTableTutorial">
    <head>
        <title>ng-table with infinite scroll</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
        <script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.2/angular.js"></script>
        <script src="http://netdna.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js" type="text/javascript"></script>
        <script src="https://rawgit.com/esvit/ng-table/master/dist/ng-table.min.js"></script>
        <script src="https://raw.githubusercontent.com/BinaryMuse/ngInfiniteScroll/1.0.0/build/ng-infinite-scroll.min.js"></script>
        <link rel="stylesheet" href="https://rawgit.com/esvit/ng-table/master/dist/ng-table.min.css">
        <link href="http://netdna.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet" media="screen">
 
        <script src="app/resources/js/app.js" type="text/javascript"></script>
        <link href="app/resources/css/style.css" rel="stylesheet" type="text/css"/>
    </head>
    <body style="padding: 50px">
        <div ng-controller="tableController">
        </div>
    </body>
</html>

As you can see I just put the links to: JQuery, Angular, bootstrap, ng-table and ngInfiniteScroll. There’s also the app.js and style.css, which I created to put my code on them.

Note that the body is still empty for now, let’s leave it like this and open our app.js, the first thing we need to do is to create our angular module and controller, just copy the following code to your app.js:

1
2
3
4
angular.module('ngTableTutorial', ['ngTable','infinite-scroll'])
        .controller('tableController', function ($scope, $filter, ngTableParams) {
        }
);

Don’t forget to declare the ngTable and infinite-scroll as dependencies, we’re going to use them later. This code is still very simple, I just created a module called ngTableTutorial, if you go back to the index.html code you’ll see that the ng-app=”ngTableTutorial” is already there in the html tag, and I also created a controller called tableController, again if go to the index.html there will be a div inside our body with the attribute ng-controller=”tableController”.

Now we need some data to be displayed to the table, I personally like mockaroo to generate random data, but feel free to generate it as you like, you’ll need about 1000 rows for this tutorial, after you generate it, just put it in a variable inside you controller, like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
$scope.users =
        [{
                "id": 1,
                "first_name": "Theresa",
                "last_name": "Morris",
                "email": "tmorris0@myspace.com",
                "country": "Indonesia",
                "ip_address": "143.220.154.199"
            }, {
                "id": 2,
                "first_name": "Steve",
                "last_name": "Gray",
                "email": "sgray1@nytimes.com",
                "country": "Norway",
                "ip_address": "163.199.165.94"
            }
           .
           .
           .
            {
                "id": 1000,
                "first_name": "Gloria",
                "last_name": "West",
                "email": "gwest2@go.com",
                "country": "China",
                "ip_address": "16.171.225.220"
            }
];

Now that we have the data we’re ready to create our table, copy the table bellow inside your div with the ng-controller attribute:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<table infinite-scroll="getMoreData()" ng-table="tableParams" show-filter="true" class="table table-striped">
    <tr ng-repeat="user in data">
        <td data-title="'Id'" sortable="'id'">
            {{user.id}}
        </td>
        <td data-title="'First Name'" sortable="'first_name'" filter="{ 'first_name': 'text' }">
            {{user.first_name}}
        </td>
        <td data-title="'Last Name'" sortable="'last_name'" filter="{ 'last_name': 'text' }">
            {{user.last_name}}
        </td>    
        <td data-title="'e-mail'" sortable="'email'">
            {{user.email}}
        </td>    
        <td data-title="'Country'" sortable="'country'">
            {{user.country}}
        </td>    
        <td data-title="'IP'" sortable="'ip_address'">
            {{user.ip_address}}
        </td>    
    </tr>
</table>

Each column is displaying one attribute of our JSON, I put the attribute sortable and filter in some of them to add the sorting and filtering features to the datatable (to show the filter you also have to put show-filter=”true” in your table). But what is important here is the attributes ng-table=”tableParams” and infinite-scroll=”getMoreData()” from the table, the first is binding the table to the tableParams variable in our controller (I’m still going to create this variable), and the second attribute receives the method that will be called when the user reaches the bottom of the page, that’s the method that will make our infinite scroll work.

Now the only thing left for us to do is to create our tableParams and implement the getMoreData() method, copy the following code bellow our JSON in your controller:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
$scope.tableParams = new ngTableParams({
    page: 1,
    count: $scope.users.length
}, {
    counts: [],
    total: 1,
    getData: function ($defer, params) {
        $scope.data = params.sorting() ? $filter('orderBy')($scope.users, params.orderBy()) : $scope.users;
        $scope.data = params.filter() ? $filter('filter')($scope.data, params.filter()) : $scope.data;
        $scope.data = $scope.data.slice(0, 20);
        $defer.resolve($scope.data);
    }
});
 
$scope.getMoreData = function () {
    $scope.data = $scope.users.slice(0, $scope.data.length + 20);
}

In this code we are instantiating the ngTableParams, the fist object it receives as a parameter is just defining that the current page is 1 and setting the row count, but what really matters here is the function getData, it will be called on the table initialization and also every time we sort or filter it, the lines 8 and 9 contains the logic to sort and filter the data, note that in line 10 I’m getting only the first 20 rows of our data, I’m doing this because every time this method is called, or the user will be filtering the data or he’ll be sorting it, both actions require him to be on the top of the page, thus I don’t need to show more than 20 rows.

Ok, now we just need to load more rows when he reaches the bottom of the pages, take a look at line 16, it’s just adding 20 more rows to our data, note that I’m using 2 variables here: $scope.data and $scope.users. The last one contains our original data, we cannot modify it, otherwise we’ll lose the data, that’s why we need an auxiliary variable, just to manipulate the data.

That’s it, now if you run your project you should see the following result:

ngTable with Infinite scroll
ng-Table with infinite scroll

As you scroll down you’ll see that the scroll bar will get smaller and smaller.

Tutorial: Custom ListView with ImageViews and TextViews

There is no doubt that the ListView is one of the most used Android UI components, in most cases developers find themselves in a situation where they need to customize this component, instead of just showing a list of Strings on the screen they also need to show more information, an ImageView, or even a Button.

In this tutorial I’m going to show how easy it is to customize a ListView, I’ll create a Contact List app with a customized ListView that will display the contacts, instead of just showing the name it’ll also show the phone number and the picture, the result will be like the customized ListView in the image bellow:

Customized ListView
Standard ListView x Customized ListView

As you can see in the image, we’re going to use 2 TextViews and 1 ImageView in this list, so let’s start by creating our ListView component, when we create the Android project it already comes with an activity_main.xml file, that’s where we’re going to add our ListView code.

1
2
3
4
5
6
7
8
9
10
11
12
13
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">
 
    <ListView
        android:id="@+id/list"
        android:layout_height="wrap_content"
        android:layout_width="match_parent">
    </ListView>
</RelativeLayout>

There’s really nothing special here, we’ve just created the ListView and gave the id “list” to it, you could give any id you want, but you should remember it, we are going to use it later.

The next step is to create another xml file that will be our custom layout, let’s call it contactlist.xml, it should look like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal" >
    <ImageView
        android:src="@drawable/person"
        android:layout_width="@dimen/picture_width"
        android:layout_height="@dimen/picture_height" />
 
    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical">
        <TextView
            android:id="@+id/contactName"
            android:layout_marginLeft="@dimen/margin"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:paddingTop="5dp"/>
 
        <TextView
            android:id="@+id/contactPhone"
            android:layout_marginLeft="@dimen/margin"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:paddingTop="5dp"/>
    </LinearLayout>
</LinearLayout>

It’s just like the first one, but with a few more things, this is the layout that is going to be used to display each of ListView items, you can add as many components as you want to this file, but in this example I’ll keep it simple and use just an ImageView and two TextViews like I said before. Don’t forget to give an id to each component. You’ll also need an image to be displayed on the ImageView, pick one of your preference and put it on the drawable folder, them you should be able reference it in the ImageView src attribute.

Now that our views are done, we can go on and start writing some Java code, the first class we need to create is the Contact.java, it’ll only contain the name and phone attributes.

1
2
3
4
5
6
7
8
9
10
11
12
public class Contact {
 
    private String name;
    private String phone;
 
    public Contact(String name, String phone) {
        this.name = name;
        this.phone = phone;
    }
 
    //GETTERS AND SETTERS
}

Really simple, there’s not much to explain here, all of you should already be familiar with Java.

Now we’re going to create our Adapter, this will be the class responsible for getting the data from our List and putting it into our UI components, let’s call it “ContactsAdapter”:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
public class ContactsAdapter extends ArrayAdapter<Contact>{
 
    int resource;
    String response;
    Context context;
 
    public ContactsAdapter(Context context, int resource, List<Contact> items) {
        super(context, resource, items);
        this.resource=resource;
    }
 
    @Override
    public View getView(int position, View convertView, ViewGroup parent)
    {
        LinearLayout contactsView;
        Contact contact = getItem(position);
        if(convertView==null) {
            contactsView = new LinearLayout(getContext());
            String inflater = Context.LAYOUT_INFLATER_SERVICE;
            LayoutInflater vi;
            vi = (LayoutInflater)getContext().getSystemService(inflater);
            vi.inflate(resource, contactsView, true);
        } else {
            contactsView = (LinearLayout) convertView;
        }
        TextView contactName =(TextView)contactsView.findViewById(R.id.contactName);
        contactName.setTypeface(null, Typeface.BOLD);
        contactName.setTextSize(TypedValue.COMPLEX_UNIT_PX,18);
        TextView contactPhone = (TextView)contactsView.findViewById(R.id.contactPhone);
        contactPhone.setTextSize(TypedValue.COMPLEX_UNIT_PX,14);
        contactName.setText(contact.getName());
        contactPhone.setText(contact.getPhone());
        return contactsView;
    }
}

This is a little bit more complicated, there’s quite a lot of things happening here, first note that I’m extending the class ArrayAdapter, we must do this, otherwise our application won’t recognize it as an adapter. Now let’s take a look at the getView method, in the lines 26 and 29 we’re getting the two TextViews from the contactlist.xml by its ids, at this moment we can modify every attribute of these components, as an example I modified the textSize in the lines 28 and 30 and also the typeface in the line 27. But the most important thing in this method is happening on the lines 31 and 32, that’s where I got the values “name” and “phone” from my Contact and passed them to my TextView objects.

Ok, now that we have an Adapter we should be able to write the code that will tie everything together, let’s open our MainActivity.java, we’re only going to modify the onCreate method:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
    ListView listView;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        List<Contact> contacts = new ArrayList<Contact>();
        contacts.add(new Contact("Gloria Miller","86-(216)605-9056"));
        contacts.add(new Contact("Teresa Garrett","86-(131)666-7051"));
        contacts.add(new Contact("Jeremy Diaz","370-(899)196-6943"));
        contacts.add(new Contact("Rose Henry","420-(240)605-2163"));
        contacts.add(new Contact("Maria Kelly","62-(488)190-3222"));
 
        listView = (ListView) findViewById(R.id.list);
        ContactsAdapter adapter = new ContactsAdapter(this,
                R.layout.contactlist, contacts);
        listView.setAdapter(adapter);
    }

In this method I’m creating the contact list and adding each item to it, in this case I’ve hard-coded the data in this class, but in a real scenario it would have come from a database or a web service. Next we need to get our ListView, we’re going to get it by its id, exactly like we did before with the TextViews, and the last step is to instantiate our Adater, its constructor will receive our contactlist.xml and the data as parameters.

That’s it! Now if you run your app the result should be exactly like the image in the beginning of the post.

How to Deal with Technology Shifts

It isn’t new that we live in a constantly changing world, especially when it comes to technology, every day new frameworks, applications and APIs comes up, making it really hard for developers to keep up with the market and all its emerging technologies, so what can we do to not be left behind in this ever-changing world?

Certainly, we cannot turn our back on new technology, one of the solutions adopted by many developers is to jump headfirst into every new framework that gets enough friction, that’s because they don’t want to be an outdated professional, they know their current job may not last forever, and also that there may be better ones out there, for this reasons they choose to be prepared for the market and every opportunity it holds, but the problem is that they put a lot of time and effort studying and learning new technology, when they finally get to an advanced level, something new emerges, and everything they just learned falls into disuse, consequently they have to learn everything again, and this cycle goes on forever.

People will argue that this is how it’s supposed to be, technology changes overtime and if you are a software developer you’ll have to find a way to change and evolve with it.

I totally agree, but the question is: How can developers deal better with change? How to smartly invest time and money learning something that will probably be out of the market in a few years?

Unfortunately there is no easy answer for that, undoubtedly you’ll go crazy if you try to be the guy who knows everything about every new framework, it’s simply too much to learn and the market won’t give you enough time. A better solution might be not to dive very deep into it, at least at first. Let’s say a new framework just came into the market, you shouldn’t get obsessed and spend all of your precious time learning it, at this moment you are not trying to be an expert yet. You can start by simply just being familiar with its main features, know how and when to use them, basically what you need is to have a good grasp of the main concepts and ideas, just enough for you to be able to show a great understanding about it, nothing too advanced for now.

After you reach that level you can stop spending time on it for the moment, keep this new framework on your pocket and go explore some others, when you come across an opportunity to use it (e.g., a new project or a new job offer) you will easily be able to do so, from that moment forward your hard work will start to pay off, then you can safely invest more time, go much deeper, get some experience and become an expert on that specific framework.

By doing that with every new framework that comes into view, or at least a great portion of them, you’ll not only be aware of everything that is happening but you’ll also have a great overview of what’s in the market. Each framework has its own advantages and disadvantages, and because you went over lots of them you’ll be capable of effectively picking the most convenient when starting a new project, of course there will be some that you’ll never going to use, probably because they didn’t fit on any of your projects, therefore you’ll never get to an advanced level at those, but that’s ok, you didn’t spend too much time on them anyway, the great thing is that most of your time was spent in those that were actually useful to you.

The truth is, one cannot be an expert in everything that comes up, more sophisticated frameworks are being created all the time, and newer ones will be even before you have a chance to learn the old ones. As we all know, technology moves fast, you must wisely choose what you’re going to learn, and once you do, if you effectively manage your time spending most of it on what really matter, I ensure you that you’ll be prepared for everything the market can throw at you.

https://plus.google.com/u/0/106915634326132202910

Managing Database Connections with Wildfly

Today’s tutorial will be about how to manage database connections on the application server, there are people who prefer to do it on the application, but I personally think it’s much better to delegate this task to the application server, that’s because you don’t need to modify and redeploy your applications every time you update your db connection info, since this information is on the server you can modify it as much as you want without touching and interrupting your applications.

The video bellow explains how to create connection pools in Wildfly, it’s from Claudio Barbosa’s Youtube channel, a new and very promising channel that’s still on it’s early days, its goal is to provide a great variety of video tutorials covering lots of well known web development tools, frameworks and APIs. You should check it out, there will be lots of videos coming up on the next days!