Posts on this Category



An Alternative to Amazon EC2

digital_ocean
DigitalOcean Homepage

Before I begin, I just want to make it clear that I’m not trying to say that DigitalOcean is better than AWS, I know that its API is nowhere near Amazon, but I realized that there is a lot of AWS users that don’t use most of its features, sometimes not even 10% of what they offer, for this reason I decided to write this post and present this alternative that may be a better option for a lot of people.

It has been a few months now since I started using DigitalOcean, at first when I was deciding which service to use my intention was to use AWS, since it is a major cloud computing services provider having a great variety of services I thought it would be the best option for me, but then I had some problems with it (with the technical support more specifically), for this reason I started looking for some alternatives, after searching a little bit I found several options, but one that caught my attention was DigitalOcean, firstly because of its simplicity, it’s really very easy and fast to set up a server(it takes less than a minute), and secondly because of the prices, they show the monthly price instead of hourly, and some of the plans are cheaper than its Amazon EC2 equivalents (Depending on the region), and you even get $10 free credit when you sign up. Of course it doesn’t offer as many features as AWS does, but since you’re not running extremely large and heavy applications you should probably be ok, you won’t need these advanced features.

DigitalOcean uses only SSD hard drives drastically increasing its performance, it also has data centers all over the world, and it offers you the possibility to choose the location that suits you the most, you can also transfer your droplet from one location to another if you like. One of the its best advantages is scalability, at first you can start with the most basic and cheap plan, then as your demand increases you can easily upgrade your plan to meet your new demands.

During these first few months I can say that my server was available more than 99% of the time, there were only two occasions when it was down for maintenance, but it was really quick, and they sent me an e-mail notifying me about it.

Overall DigitalOcean is an excellent server, I’ve seen a lot of people saying the same thing, if you read some reviews you see that the great majority of them are good, so if you are looking for a server to host your applications I thing DigitalOcean really deserves a shot.

For more information visit the DigitalOcean Official Site.

Getting Started with Facebook’s React and Flux

reactjs flux
ReactJS Homepage

React and Flux are two of the most promising technologies of the present days, both are constantly showing up on trending technologies lists, quickly gaining market and becoming popular among developers. The first one defines itself as an open source javascript library for building user interfaces, it is an excellent tool for developers to create highly dynamic UI components, as the second is a brand new application architecture for client-side web apps designed to work together with React by using unidirectional data flow.

Let’s start by talking a little bit more about React with an example, and later on I’ll give more details about Flux and apply it to the first example.

Creating our first Application with React

The example bellow is a classic Hello World example using react:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<!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 HelloWorld = React.createClass({
		     render: function() {
		       return <div>Hello World!!</div>;
		     }
		   });
 
		   React.render(<HelloWorld />, document.getElementById('component'));
 
	   </script>
   </body>
</html>

If you carefully analyze the code, the first different thing you should notice is the new script type text/jsx, which is basically Javascript with some HTML elements.

You can also see that I had to add three scripts to my page, the first and the second are the React and JSX scripts respectively, and the third one is jQuery, I’ll explain in a moment why we need it.

Now let’s analyze the code and see how it works, take a look at the declaration of HelloWorld var, this is the variable that will actually hold our new component. In React we always have to create the specification of our components through the function React.createClass, it receives an object as a parameter containing a render function, this function will process and return the component’s HTML code the way it’ll be displayed on the browser, in this example I’m just returning a div with a text within it, nothing dynamic for now.

After implementing our component we need just one more line of code to make it appear on the page, to show it we have to call React.render (line 19 of the example), this function receives two parameters, the first one is the component that will be displayed and the second one is where we want to display it, this is where JQuery will come into action, note that right after the body declaration we have a div with the id=component, I’m using JQuery’s getElementById to get this div and render my HelloWorld component on its place. Now if you run this application you should see ‘Hello World!!’ on your page.

Using Flux Architecture

flux architecture
Flux Homepage

As I said before Flux is a new architecture used by Facebook that complements React components by using unidirectional data flow, it is divided in four parts: the dispatcher, stores, views and controller-views. Every action, no matter where it comes from, is received by the dispatcher which will be responsible for changing the state of the appropriate store, after the state is modified it will notify the controller-view that will retrieve the new data and update all its child views.

Here is as brief explanation for each one of the components:

Dispacher – Is the central component that manages the data flow within the application, it distribute the actions to the appropriate stores.
Store – Components that contains the logic and state of the application.
View – The components that represent the user interface.
Controller-view – The type o view the listens to events coming from the stores.

It may be hard to understand at first but once you see an example it will get easier. To illustrate how this architecture works I’m going to use the same preview example but slightly modified just enough to demonstrate how Flux works, so instead of just showing ‘Hello World!!’ on the page we’re going to render a button that will trigger an action and show the hello world message, the difference is that now we have an action involved.

First we’re going to move our react code to another file that, it’ll be called HelloWorld.jsx, it should look like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
var React = require('react');
var HelloWorldAction = require('../Actions/HelloWorldAction.js');
 
var HelloWorld = React.createClass({
	showMessage:function(){
		HelloWorldAction.showMessage('Hello World!!');
	},
	render: function() {
		return <a onClick={this.showMessage}>Click Here</a>;
	}
});
 
module.exports = HelloWorld;

I’ve already made the changes, now I’m rendering a link that when clicked will trigger the showMessage function and pass our message to HelloWorldAction, which will be responsible to delivery it to the dispatcher, here is the HelloWorldAction code:

1
2
3
4
5
6
7
8
9
10
11
12
var Dispatcher = require('../Dispatcher/AppDispatcher.js');
 
var HelloWorldAction = {
	showMessage:function(message){
		Dispatcher.handleViewAction({
			actionType:'SHOW_MESSAGE',
			message:message
		});
	}
}
 
module.exports = HelloWorldAction;

Here I’m just wrapping my message that in this case will be my payload, and I’m also assigning an actionType to it, then I’m passing this action to the dispatcher:

1
2
3
4
5
6
7
8
9
10
11
12
13
var Dispatcher = require('flux').Dispatcher;
var assign = require('object-assign');
 
var AppDispatcher = assign(new Dispatcher(),{
	handleViewAction:function(action){
		this.dispatch({
			source:'VIEW_ACTION',
			action:action
		});
	}
});
 
module.exports = AppDispatcher;

This is the dispatcher code, here we have the implementation of the handleViewAction function that is receiving the payload from the HelloWorldAction, the purpose of this is to broadcast it to the stores, then the appropriate store can perform the action.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
var Dispatcher = require('../Dispatcher/AppDispatcher.js');
var EventEmitter = require('events').EventEmitter;
var assign = require('object-assign');
 
var AppStore = assign({},EventEmitter.prototype,{
	emitChange:function(){
		this.emit('change');
	}
});
 
AppDispatcher.register(function(payload){
	alert(payload);
});
 
module.exports = AppStore;

Lastly we have our store, here I’m implementing and registering in the dispatcher the method that will actually show the message.

That’s it, now before you run it, since we used jsx code, you have to use browserify and reactify to compile it.

I know I didn’t give too much details on this tutorial, this application is so simple that it’s kind of weird to write that much code just to show a hello world message, I’m looking forward to write another post with a more complex application, this way we can explore react and flux a little further.

Node.js Tutorial: Reading and Writing files

Reading and writing files is a very trivial task, no matter what programming language you use you probably have already came across a situation where you had to do it, and it’s not different for node.js developers, luckily node.js makes this task very easy for us, with the file system(fs) module we can easily read files with very few lines of code as the following example:

1
2
3
4
5
6
7
var fs = require('fs');
 
fs.readFile('C:\\file.txt', 'utf8', displayData);  
 
function displayData(err,data){
  console.log(data);
}

In the example above I’ve just used the fs.readFile function to read a file located on my ‘C:\’, besides the file path I also provided the encoding and a callback which will be called once the file content is ready.

Now that we already know how to read files, let’s learn how to write files, it’s as easy as reading them, take a look at the following code:

1
2
3
4
5
6
7
8
9
10
11
var fs = require('fs');
 
fs.writeFile('C:\\file.txt', 'My Content', showMessage);  
 
function showMessage(err){
  if(err) {
    console.log(err);  
  }else{
    console.log('Your data has been successfully written!');    
  }
}

It’s basically the same thing we saw on the first example, except that instead of using the readFile function I used the writeFile, also the second argument is the content I want to write on the file, and once again we have a callback that will execute after the content is written.

If you run this code more than once you should note that before writing your content it erases everything that is already on the file, to prevent this from happening you should use the function appendFile instead of writeFile.

AngularJS Tutorial: ui-router example

Since ui-router is one of the most useful features that angular can provide I decided to write this tutorial just to show how to use it, I’m going to create a very simple application that illustrates how to create templates using ui-router states.

After donwloading angular.min.js and angular-ui-router.min.js let’s create our index.html and include both:

1
2
3
4
5
6
7
8
9
10
11
12
<!DOCTYPE html>
<html ng-app="uiRouterExample">
    <head>
        <title>ui-router example</title>
        <script src="js/angular.min.js" type="text/javascript"></script>
        <script src="js/angular-ui-router.min.js" type="text/javascript"></script>
        <script src="js/app.js" type="text/javascript"></script>
    </head>
    <body>
        <div ui-view></div>
    </body>
</html>

This file will be our template, it will be the same no matter the state, note that inside the body I have a div with the ui-view attribute, that’s where our states will be included.

With the index.html ready let’s create the app.js:

1
2
3
4
5
6
7
8
9
10
11
var app = angular.module('uiRouterExample', ['ui.router']);
app.config(function ($stateProvider, $urlRouterProvider) {
    $stateProvider.state("state1", {
        url: "/state1",
        templateUrl: "states/state1.html"
    }).state("state2", {
        url: "/state2",
        templateUrl: "states/state2.html"
    });
    $urlRouterProvider.otherwise("/state1");
});

I tried to make this code as simple as possible, I’ve just created 2 states named ‘state1′ and ‘state2′, each one of them receives an object containing the attributes ‘url’ and ‘templateUrl’, the first one is the path we’re going to type on our browser to call the states, and the second is the html file that will be displayed when the state is called.

Lastly I’m making state1 the default state by passing its path to $urlRouterProvider.otherwise function, this way when the application is first loaded the state1 will be called by default.

Now let’s take a look at out state1.html and state2.html:

1
2
3
4
5
6
7
8
9
<!--state1.html-->
This is the State1
<br />
<a ui-sref="state2">Go to state2</a>
 
<!--state2.html-->
This is the State2
<br />
<a ui-sref="state1">Go to state1</a>

If you run your project, since state1 is your default state, you’re going to see the state1.html rendered on your screen, and if you click on the link you’re going to be redirected to state2.

Tutorial: Creating Node.js modules

Node.js Modules

In this short tutorial I’m going to explain how you can create your own modules in Node.js, as everyone knows we cannot keep our entire code in only one js file, as your application grows it’ll be almost impossible for you to maintain your code, for this reason it’s essential that we separate our code in modules, this way it’ll hopefully always be organized and easy to maintain.

Node.js makes it very easy for us to create custom modules, let’s suppose we need to put 2 functions in a separated module, we just need to create a new js file like this:

newModule.js

1
2
3
4
5
6
7
exports.function1 = function(){
	console.log('Function 1');
}
 
exports.function2 = function(){
	console.log('Function 2');
}

As you can see it’s a very straightforward code, all I did was to create 2 functions and add them to module.exports, unless you don’t want your functions to be visible to other modules it’s very important that you add them to exports.

Now you can require this new module in another module as follows:

app.js

1
2
3
4
var newModule = require('./newModule');
 
newModule.function1();
newModule.function2();

When requiring a module you have to pass its full path to the require function, in this example I’m assuming that the 2 js files are in the same folder. After requiring your module you’re done! Now this app.js file has access to all the functions you’ve exported from your new module.

Tutorial: Creating Reusable Code with AngularJS Directives

AngularJS Directives

I know this may not be new for most of you, but when it comes to directives a lot of people still get really confused, so let’s start by looking at its definition, according to AngularJS documentacion:

Directives are markers on a DOM element (such as an attribute, element name, comment or CSS class) that tell AngularJS’s HTML compiler ($compile) to attach a specified behavior to that DOM element or even transform the DOM element and its children.

In other words, they allow us to create our own DOM elements that can be reused all over the place, imagine that you have a block of HTML code that you know you’re going to use in several places, instead of just coping and pasting it everywhere, you can create a directive and use it wherever you need, it’ll be a lot easier for you to maintain your code, if something changes in this HTML block you just have to modify your directive, and the changes will reflect across your application.

It will be easier to understand with an example, let’s create a project containing the following files:

index.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<!DOCTYPE html>
<html ng-app="directivesTutorial">
    <head>
        <title>TODO supply a title</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.2/angular.js"></script>
        <script src="app/resources/js/app.js" type="text/javascript"></script>
    </head>
    <body >
        <div ng-controller="directivesTutorialController">
            <div ng-repeat="company in companies">
                <p>Company: {{company.name}} - City: {{company.city}}</p>
            </div>
        </div>
    </body>
</html>

app.js

1
2
3
4
5
6
7
8
9
10
11
12
13
var app = angular.module('directivesTutorial', []);
app.controller('directivesTutorialController', function ($scope, $http) {
    $scope.companies = [{"id": 1, "name": "Mymm", "city": "Pantano do Sul"},
        {"id": 2, "name": "Skyble", "city": "Guilmaro"},
        {"id": 3, "name": "Tagfeed", "city": "Gnosjö"},
        {"id": 4, "name": "Realcube", "city": "Jrashen"},
        {"id": 5, "name": "Bluejam", "city": "Zhangjiawo"},
        {"id": 6, "name": "Jayo", "city": "Obonoma"},
        {"id": 7, "name": "Cogidoo", "city": "Sungsang"},
        {"id": 8, "name": "Avavee", "city": "Diawara"},
        {"id": 9, "name": "Tagtune", "city": "Monywa"},
        {"id": 10, "name": "Centimia", "city": "Retkovci"}];
});

Nothing different for now, we’ve seen this a million times, it’s just a ng-repeat iterating over a JSON (in this case a list of campanies), note that inside the ng-repeat div we have a small block of code that displays the company information, of course this block would be more complex in a real scenario, but let’s suppose we need to reuse it to display the same data in other parts of the application, to achieve that we’re going create a directive called ‘company’ which will be responsible for displaying the company data.

Copy the code bellow to another js file, let’s call it ‘campany.js':

1
2
3
4
5
6
7
8
var companyDirective = angular.module('directives.company', []);
companyDirective.directive('company', function () {
    return{
        retrict: 'E',
        scope: {object: '='},
        templateUrl: "templates/company.html"
    };
});

That’s our directive’s code, you can see that it returns an object containing 3 attributes, the first one is the “retrict: ‘E'”, it means that our directive will be restricted to elements, in other words it will be a DOM element.

The second one is the “object: ‘='”, by declaring this ‘object’ variable we’re saying that our directive will have an attribute called ‘object’, we’re going to use this attribute to pass the company we want the data to be displayed.
And lastly we have our templateUrl that receives the path to an html file containing the directive’s html code.

Our company.html should look like this:

1
<p>Company: {{object.name}} - City: {{object.city}}</p>

Note that it’s the same code as before, the only difference is that instead of using the variable ‘company’ we’re using ‘object’ which is the name of the attribute we defined before.

We’re almost done, now you just have to add to your index.html a reference to company.js:

1
<script src="{YOUR_PATH}/company.js" type="text/javascript"></script>

and also put the directive as a dependency in your app.js:

1
var app = angular.module('directivesTutorial', ['directives.company']);

That’s it! Now our ng-repeat can be rewritten using our new directive:

1
2
3
<div ng-repeat="company in companies">
    <company object="company"></company>
</div>

You now have the ‘company’ element that can be reused anywhere in your application.

Related Posts:
Tutorial: Basic DataTable (sorting, filtering and pagination) with AngularJS and ng-Table
Tutorial: Implementing Infinite Scroll with AngularJS and ngInfiniteScroll

MongoDB Basics (Select, Insert, Update and Delete)

MongoDB is a NoSQL, cross-plataform, document-oriented database, it was first developed in 2007 and has gained a lot of friction ever since. In this tutorial we’re going to go over all the basic CRUD operations with mongoDB, which are: Select, Insert, Update and Delete.

Before we begin make sure you have your MongoDB correctly installed and also a connection established, with your environment set let’s get started by creating our first collection and inserting some data on it.

Inserting Data

MongoDb works with JSON-like documents, so we’re going to pass the data in this format. The first thing we need to know is the collection that we’re going store the data (collections are equivalent to tables in relational databases), for this example I’m going to use the collection “users”, note that I haven’t created it yet, mongo will automatically do it for me when I insert the data on it for the first time:

1
2
3
4
5
6
> db.users.insert([
{"id": 1, "first_name": "Joshua", "last_name": "Black", "email": "jblack0@nifty.com", "country": "Philippines"}, 
{"id": 2, "first_name": "Carol", "last_name": "Hall", "email": "chall1@reddit.com", "country": "Philippines"}, 
{"id": 3, "first_name": "Phillip", "last_name": "Fisher", "email": "pfisher2@symantec.com", "country":"Portugal"}, 
{"id": 4, "first_name": "Marie", "last_name": "Mills", "email": "mmills3@hhs.gov", "country": "Greece" }
])

After executing the command you should see the following output:

1
2
3
4
5
6
7
8
9
10
BulkWriteResult({
        "writeErrors" : [ ],
        "writeConcernErrors" : [ ],
        "nInserted" : 4,
        "nUpserted" : 0,
        "nMatched" : 0,
        "nModified" : 0,
        "nRemoved" : 0,
        "upserted" : [ ]
})

It means that you’ve successfully inserted four rows in your collection, now that we already have some data let’s learn how to query them.

Selecting and Filtering Data

To select the documents from a collection we can use the find() method, here are some examples of its usage:

Bring all the data:

1
> db.users.find()

Filter by an attribute:

1
> db.users.find({"id":1})

AND condition:

1
> db.users.find({"country":"Philippines","first_name":"Carol"})

OR condition:

1
> db.users.find({$or:[{"country":"Greece"},{"country":"Portugal"}]})

$lt and $gt operators (< and >):

1
2
> db.users.find({"id":{$lt:2}})
> db.users.find({"id":{$gt:2}})

Updating Data

MongoDB provides the method update() to perform documents modifications, we can pass the filters as the first parameter, mongo will update only the documents that matches with them, in the example bellow I’ve passed {“id”:1} as the first argument, which means I want to update only the documents with id = 1. The second parameter is where we pass the actual modifications, I’m changing the first_name to “Phill” and the country to “Italy”.

1
2
3
4
5
6
7
8
9
db.users.update(
    {"id":1}, 
    {
        $set:{
           "first_name":"Phill",
           "country":"Italy",
       }
    }
)

This will be the output:

1
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

Removing Data

Lastly we’re going to remove the documents with the method remove(), its usage is quite like the find() method, we can use it with no arguments to remove all the documents or we can specify a condition:

Remove all the data:

1
> db.users.remove()

Remove with a condition:

1
> db.users.remove({"id":1})

For more information see the MongoDB Manual.

Java 8: Simple Example of First-class Functions

A first-class object (or first-class citizen) in programming languages can be defined as an entity that supports the following operations: being passed as a parameter, being assigned to a variable and being returned from a function. In other words, everything that contains a value can be considered a first-class citizen.

In the previous versions of Java we had the following elements as first-class objects:

Primitive values: int, double, long, short, byte, char, etc.
Objects: new Integer(1), new ArrayList(), new Person(), etc.

Methods and classes, since they’re not values, were considered second-class.

Now with Java 8, functional-style programming was introduced to the “Java World”, methods can now be treated as values, which means that now, like in Scala and JavaScript, they’re also first-class citizens and they can be passed as parameters, assigned to variables and also returned from functions.

Here is a simple example of how to use this Java 8 feature:

Let’s suppose we have a list of objects and we want to filter it by some specific attribute, this is the conventional way to do it:

1
2
3
4
5
6
7
8
9
public List filterPersonByAge(List<Person> list) {
        List result = new ArrayList();
        for (Person person : list) {
            if(p.age > 65){
                result.add(person);
            }
        }
        return result;
}

In this case I’m just filtering and returning everyone with age greater than 65, the problem is that if I need to filter this list again by another attribute I’ll have to duplicate this code and modify just one single line. That’s exactly the advantage of Java 8 first-class functions, by using them we don’t have to duplicate the code.

Here is the same method rewritten using first-class functions:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import java.util.function.Predicate;
 
public class FirstClassFunctionExample {
 
   public List filterPerson(List<Person> list, Predicate<Person> p) {
       List result = new ArrayList();
       for (Person person : list) {
           if(p.test(person)){
               result.add(person);
           }
       }
       return result;
   }
 
   public boolean ageFilter(Person p){
       return p.age > 65;
   }
}

Note that I’ve added a new parameter of the type Predicate, which will be the value that contains the condition I’m going to test in the line 8. I’ve also implemented the ageFilter method, which is the one I’m going to pass as the parameter ‘p’.

And finally, this is how we call the filterPerson method passing ageFilter as a parameter:

1
2
 
filterPerson(personList, FirstClassFunctionExample::ageFilter);

That’s it! Now if I need to filter by another attribute I just have to change a little bit the filter implementation (or write another filter), the method that will actually filter the list will be reused.

Source: Java 8 in Action

Tutorial: Implementing Infinite Scroll with AngularJS and ngInfiniteScroll

Over the past few years the infinite scroll has became very popular across the web, developers are increasingly choosing to use infinite scroll over the conventional paginator. The advantage is that it doesn’t require the user to manually go to the next page when he reaches the end of the page, it automatically loads and display more data without the user intervention.

In this tutorial I’m going to show how to implement infinite scroll using ngInfiniteScroll for AngularJS.

First create the js and html file:

app.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
angular.module('infiniteScrollTutorial', ['infinite-scroll'])
        .controller('infiniteScrollController', function ($scope, $http) {
            $scope.users =
                    [{
                            "id": 1,
                            "first_name": "Kimberly",
                            "last_name": "Grant",
                            "email": "kgrant0@ebay.co.uk",
                            "country": "Bolivia",
                            "ip_address": "93.77.148.179"
                        }, {
                            "id": 2,
                            "first_name": "Elizabeth",
                            "last_name": "Lewis",
                            "email": "elewis1@so-net.ne.jp",
                            "country": "Indonesia",
                            "ip_address": "39.187.159.25"
                        },
                        .
                        .
                        .
 
                        {
                            "id": 100,
                            "first_name": "Shawn",
                            "last_name": "Ellis",
                            "email": "sellis2r@diigo.com",
                            "country": "Portugal",
                            "ip_address": "121.250.152.235"
                        }];
});

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
34
35
36
37
38
39
40
<!DOCTYPE html>
<html ng-app="infiniteScrollTutorial">
    <head>
        <title>TODO supply a title</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="https://raw.githubusercontent.com/BinaryMuse/ngInfiniteScroll/1.0.0/build/ng-infinite-scroll.min.js"></script>
        <script src="app/resources/js/app.js" type="text/javascript"></script>
        <style>
            .userContainer{
                width:500px;
                height:110px;
                background: #f9f9f9;
                padding: 5px;
                font-family: verdana;
                margin-bottom: 7px;
                box-shadow: 0px 0px 2px 1px;
            }
            .userContainer p{
                font-size: 12px;
            }
        </style>
    </head>
    <body>
        <div ng-controller="infiniteScrollController">
            <div >
                <div ng-repeat="user in users" class="userContainer">
                    <h4>{{user.first_name}} {{user.last_name}}</h4>
                    <p>
                        <b>Email:</b> {{user.email}}  -   
                        <b>Country:</b> {{user.country}}  -  
                        <b>IP:</b> {{user.ip_address}} 
                    </p>
                </div>
            </div>
        </div>
    </body>
</html>

Nothing special for now, except that I’ve already added the dependency ‘infinite-scroll’ in the angular module declaration, besides that we just have a regular ng-repeat iterating over a JSON (you should make this JSON as big as you can, it will be easier for you to see the results, you can use mockaroo to gerenate some JSON data).

Now let’s change the code a little bit to make the infinite scroll work, we’re going to add the attribute ‘infinite-scroll’ in the div above the one with the ng-repeat, after the modification it should look like this:

1
2
3
4
5
6
7
8
9
10
<div infinite-scroll="getMoreData()">
    <div ng-repeat="user in data" class="userContainer">
        <h4>{{user.first_name}} {{user.last_name}}</h4>
        <p>
            <b>Email:</b> {{user.email}}  -   
            <b>Country:</b> {{user.country}}  -  
            <b>IP:</b> {{user.ip_address}} 
        </p>
    </div>
</div>

Note that the new attribute is referencing the function getMoreData(), which will be called every time the bottom of the element approaches the bottom of the browser window, in this function we’ll have to write the code to get more data, also note the I’m not using the variable ‘users’ anymore in the ng-repeat, instead I’m using the auxiliary variable ‘data’.

Let’s take a look at the getMoreData() code, add this bellow the JSON in your app.js:

1
2
3
4
$scope.data = $scope.users.slice(0, 5);
$scope.getMoreData = function () {
    $scope.data = $scope.users.slice(0, $scope.data.length + 5);
}

I’m initializing the $scope.data with the 5 first elements of the $scope.users, and the function getMoreData is just adding five more elements every time it gets called.

Now if you run you application you’ll see the following result:

AngularJS infinite Scroll
AngularJS infinite Scroll

That’s it! At first it’ll have only 5 elements loaded and as you scroll down it will start loading more.

Related Posts:
Tutorial: Basic DataTable (sorting, filtering and pagination) with AngularJS and ng-Table
Tutorial: Creating Reusable Code with AngularJS Directives

Example of ServletContextListener Implementation

According to Oracle official documenentation, the ServletContextListener Interface is responsible for receiving notifications about the ServletContext lifecycle changes, more specifically its initialization and destruction. This can be really helpful for developers in some specific situations, like for example when we need to execute a block of code right before the application starts or shut down.

In this short tutorial I’m going give a really simple example of a ServletContextListener Implementation.

With our Java Web project created let’s create a Java class that implements the ServletContextListener interface, it should look like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package tech.fourDev.servletContextListenerSample;
 
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
 
public class ServletContextListenerSample implements ServletContextListener{
 
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        System.out.println("INITIALIZED");
    }
 
    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        System.out.println("DESTROYED");
    }   
}

This is our listener, you can see that I’ve already implemented the contextInitialized and contextDestroyed methods, as the name suggests the first one will be called when the ServletContext starts and the other one when it gets destroyed.

There is just one more thing to be done before you can run your application, you need to register this listener in your web.xml:

1
2
3
<listener>
    <listener-class>tech.fourDev.servletContextListenerSample.ServletContextListenerSample</listener-class>
</listener>

Perfect! Now if you run your application you’ll see the word “INITIALIZED” printed when you deploy your project and the word “DESTROYED” when you undeploy or redeploy it.