Include AdMob Banner on Cocos2d-x Android Game

Hi,

In this post we will show a piece of code that will help you to add an admob banner on your cocos2d-x game in android.

Firstly, you need to setup the google play services on your app.
Then you need to include on your AndroidManifest.xml the Admob activity and the required permissions.

<activity android:name="com.google.android.gms.ads.AdActivity"
         android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"/>

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>         

Then on your Activity, you need to put this piece of code on the onCreate method:


protected void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);
		AdView adView = new AdView(this);
		adView.setAdSize(AdSize.BANNER);
		adView.setAdUnitId("YOUR AD UNIT ID");

		RelativeLayout relativeLayout=new RelativeLayout(this);
		RelativeLayout.LayoutParams layoutParams1=new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
		RelativeLayout.LayoutParams layoutParams=new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
		layoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
		layoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE);
		AdRequest adRequest = new AdRequest.Builder()
		.addTestDevice("B3EEABB8EE11C2BE770B684D95219ECB")
		.build();

		adView.loadAd(adRequest);
		relativeLayout.addView(adView, layoutParams);
		this.addContentView(relativeLayout, layoutParams1);

}

I hope this help.

See you on the next post.

Redis SORT with Jedis

In this post we will talk about the Redis SORT command.

Redis provides the SORT command that we can use to retrieve or store sorted values from a LIST, SET or ZSET.

The simplest form we can use the command over a KEY like the example below:

SORT numbers_list

This will sort the values contained in the key and return them. The command sorts the values as numbers. So, lets say we have a list with the following values:

1, 110, 5

The command above will return

1 5 110

We can specify to sort the values using alphabetically using the ALPHA modifier. There are a number of modifiers. We will take a look at some of them in the examples below. The examples will use the Jedis api.

For our examples let’s consider that we have an idea management system. We have a list containing all the usernames from the system:

all:users [junior, francisco, ribeiro, user4]

And for every username there will be a hash containing the user’s information:

user:

user:junior
  - name: "Junior User"
  - num_ideas : "5"
  - email:"fjunior@email.com"

user:francisco
 - name: "Francisco User"
 - num_ideas: "4"
 - email: "francisco@email.com"

...

We can see a class that will populate redis for our example:

package br.com.xicojunior.redistest;

import java.util.HashMap;
import java.util.Map;

import redis.clients.jedis.Jedis;

public class App 
{
	
    public static Jedis jedis = new Jedis("localhost");   
    public static void main( String[] args ){
        
    	String names[] = new String[]{"junior", "francisco", "ribeiro", "user4"};
    	for(String name: names){
    		jedis.lpush("all:users", name);
    	}
    	addUserHash(names[0], "Junior User", "junior@junior.com", "5");
    	addUserHash(names[1], "Francisco User", "francisco@francisco.com", "4");
    	addUserHash(names[2], "Ribeiro User", "ribeiro@ribeiro.com", "3");
    	addUserHash(names[3], "User 4", "user@user.com", "2");
    	
    	for(String name: names){
    		System.out.println(jedis.hgetAll("user:".concat(name)));
    	}
    	
    	System.out.println(jedis.lrange("all:users", 0, -1));
    	
    	
    	
    }
    
    public static void addUserHash(String username, String name, String email, String numberOfIdeas){
    	Map<String, String> userProp = new HashMap<String, String>();
    	userProp.put("name",name);
    	userProp.put("email", email);
    	userProp.put("num_ideas", String.valueOf(numberOfIdeas));
    	
    	jedis.hmset("user:".concat(username), userProp);
    }
}

Let’s take a look at the code example below:


package br.com.xicojunior.redistest;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.SortingParams;

public class SortTest {

	public static void main(String[] args) {
		Jedis jedis = new Jedis("localhost");
		
		//[1]sorting the usernames
		System.out.println(jedis.sort("all:users"));
		//[ribeiro, francisco, junior, user4]
		
		//[2]sorting the username alpha
		//jedis sort method receives a SortingParams instance for modifiers
		System.out.println(jedis.sort("all:users", new SortingParams().alpha()));
		//[francisco, junior, ribeiro, user4]

	}

}

In the example above we sort the key “all:users“. In the first try, it doesn’t seem to have sorted correctly because the default sorting considers numbers.
On the second example, we use the ALPHA modifier. We can do this by using the overloaded version of the sort method. It receives an instance of SortingParams class. In this case we see the usernames being sorted correctly.

One nice feature of the SORT command is that we can sort the list using external values, values in other key(s). In the example below we will sort the all:users key by the number of ideas the user gave. It can be done using the “BY” modifier that receives the pattern of the keys to be used. Let’s see our example below:

package br.com.xicojunior.redistest;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.SortingParams;

public class SortTest {

	public static void main(String[] args) {
		Jedis jedis = new Jedis("localhost");
		
		//[1] Sorting the usernames by the number of ideas
		System.out.println(jedis.sort("all:users", new SortingParams().by("user:*->num_ideas")));
		//[user4, ribeiro, francisco, junior]
		
		//[1] Sorting the usernames by the number of ideas DESC
		System.out.println(jedis.sort("all:users", new SortingParams().by("user:*->num_ideas").desc()));
	}

}

In this second example, we are sorting the usernames by an external value, in our case by the field “num_ideas“. As in this case we are sorting by a hash field we used the following pattern “user:*->num_ideas“. With this pattern we are saying to look for the key “user:*” where this “*” will be replaced by the value from the list. As it is a hash we need to inform the field, we do this using the pattern “->fieldname“. If we were sorting by a string key we could use the following pattern “num_ideas_*” considering there was a key to store the number of ideas for each user.

In the first call it retrieved the values sorting them ASC, we can also tell redis to sort it DESC using the DESC modifier. With jedis BY and DESC are methods from SortingParams. As all methods returns the instance, we can chain all the callings and that makes easier to read the code.

With the SORT command we can also retrieve values from the external key or a field form an external hash. We can do this using the GET modifier, and we can use it many times. Let’s see some examples of this modifier below:

package br.com.xicojunior.redistest;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.SortingParams;

public class SortTest {

	public static void main(String[] args) {
		Jedis jedis = new Jedis("localhost");
		
		//[1] Sorting the usernames by the number of ideas and retrieving the user name
		System.out.println(jedis.sort("all:users", new SortingParams().by("user:*->num_ideas").get("user:*->name")));
		//[User 4, Ribeiro User, Francisco User, Junior User]
		
		//[2] Retrieving the name and email
		System.out.println(jedis.sort("all:users", new SortingParams().by("user:*->num_ideas").get("user:*->name","user:*->email")));
		//[User 4, user@user.com, Ribeiro User, ribeiro@ribeiro.com, Francisco User, francisco@francisco.com, Junior User, junior@junior.com]
		
		
		//[3] Retrieve the value of the key being sorted - Special pattern #
		System.out.println(jedis.sort("all:users", new SortingParams().by("user:*->num_ideas").get("user:*->name","user:*->email","#")));
		//[User 4, user@user.com, user4, Ribeiro User, ribeiro@ribeiro.com, ribeiro, Francisco User, francisco@francisco.com, francisco, Junior User, junior@junior.com, junior]
	}

}

In the code above we can see the use of the GET modifier, in order to return a hash field we can use a pattern similar to the one we used in the BY modifier.
In the first we return simply the name, as we said, we can use GET many times, in the second we retrieve the name and the email from the user. We can also, retrieve the value for the key that was sorted by using a special pattern “#”. The method get, receives a vararg so we can pass all the external keys we want to retrieve the value from.

Another thing we can do is to store the result from the sorting in a key. It is useful for cases when we want to cache the sort result, we can specify a dest key for the sort command. The result will be stored as a LIST.


package br.com.xicojunior.redistest;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.SortingParams;

public class SortTest {

	public static void main(String[] args) {
		Jedis jedis = new Jedis("localhost");
		
		jedis.sort("all:users","dest_key1");
		
		System.out.println(jedis.lrange("dest_key1", 0, -1));
		//[ribeiro, francisco, junior, user4]
		
		jedis.sort("all:users", new SortingParams().alpha().desc(), "dest_key2");
	
		System.out.println(jedis.lrange("dest_key2", 0, -1));
		//[user4, ribeiro, junior, francisco]
	}

}

One very useful feature of the SORT command is that we can use it only to get values from related keys. There is a modifier indicating to do not the sort NOSORT

package br.com.xicojunior.redistest;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.SortingParams;

public class SortTest {

	public static void main(String[] args) {
		Jedis jedis = new Jedis("localhost");
		
		System.out.println(jedis.sort("all:users", new SortingParams().get("user:*->name","user:*->email").nosort()));
		//[User 4, user@user.com, Ribeiro User, ribeiro@ribeiro.com, Francisco User, francisco@francisco.com, Junior User, junior@junior.com]
		
	}

}

This piece of code basically retrieves the name and email for all users. In case we don’t use SORT command, we would need at least two commands to do the same:

LRANGE all:users 0 -1 //TO get all usernames

and then for each username call hmget for each one like below

HMGET user:junior name email //TO get the name and email from a user

We can find the command documentation in the redis site.

That’s it for today.

See you in the next post.

Simple Message Queue using Redis

In this posts we will use Redis as a simple message queue, using list commands.

Let’s say we have an application that allows the users to upload a photo. Then in the application we display the photo in different sizes like Thumb, Medium and Large.

In a first implementation we could have the task of processing the uploaded image in the same request. As it is an expensive task, it would make our requests slow.

A possible solution for this it to make this processing asynchronous by using a Message Queue(MQ), there are a lot of well known MQs like ActiveMQ, RabbitMQ, IBM MQ and other. In the examples below we will be using Redis as a message queue using the LIST structure.

The idea is to have a LIST where the producer will put the messages to be processed and some consumers that will watch the LIST to process the messages sent.

Basically, the producers will add the messages into the end of the list with “RPUSH queue message” and the consumers will read the messages in the beginning of the list with “LPOP queue” configuring a FIFO processing.

The client will always be looking for a new message, for this purpose we will use the BLPOP command that is a blocking version of the LPOP command. Basically there will be a while loop calling BLPOP to get a new message to process.

Considering the image upload example, let’s say we have a class ImageUploader that is responsible for uploading the image to the server, it will add a new message in the queue, indicating there is an image to be processed, a message could be a JSON string like this:

{“imagePath”:”/path/to/image”, “user”:”userid”}

The ImageUploder class could be like this:


public class ImageUploader {

  public void uploadImage(HttpServletRequest request){
    
    String imagePath = saveImage(request);
    String jsonPayload = createJsonPayload(request, imagePath);
    jedis.rpush("queue", jsonPayload);
    //... keep with the processing
  }
  
  //.... other methods in the class
}

It is just an example on how the producer would work. In this case we have decoupled the image processing from the ImageUploader class. We just create a new message in the queue, so the consumers would process them.

The message consumer could be something like this:

package br.com.xicojunior.redistest;

import java.util.List;

import redis.clients.jedis.Jedis;

public class MessageConsumer 
{
    public static void main( String[] args )
    {
        Jedis jedis = new Jedis("localhost");   
        List<String> messages = null;
        while(true){
          System.out.println("Waiting for a message in the queue");
          messages = jedis.blpop(0,"queue");
          System.out.println("Got the message");
          System.out.println("KEY:" + messages.get(0) + " VALUE:" + messages.get(1));
          String payload = messages.get(1);
          //Do some processing with the payload
          System.out.println("Message received:" + payload);
        }
        
        
    }
}

This consumer code could be running in a different process or even a different machine. This consumers code is runnable we can compile it and run it using eclipse or java command.

For this code we used the jedis.blpop method, it returns a List with 2 Strings, (0) – The key, (1) – The value that was returned. The method also receives an integer, it indicates the timeout. We passed 0 indicating there will be no timeout.

When we run this code and there is no value in the list, in the console we will see just the message

"Waiting for a message in the queue". 

Then if a client adds a element in the list “queue” our consumer class will get its value. We can simulate a test by using the redis-cli or even another class that will add elements in the queue like the one below:


package br.com.xicojunior.redistest;

import redis.clients.jedis.Jedis;

public class MessageProducer {

  public static void main(String[] args) {
    Jedis jedis = new Jedis("localhost");
    
    jedis.rpush("queue", "Value 1");
    jedis.rpush("queue", "Value 2");
    jedis.rpush("queue", "Value 3");
    
    
  }
  
}

If we run the MessageProducer class after the MessageConsumer class is already running we will see this output in the console:


Waiting for a message in the queue
Got the message
KEY:queue VALUE:Value 1
Message received:Value 1
Waiting for a message in the queue
Got the message
KEY:queue VALUE:Value 2
Message received:Value 2
Waiting for a message in the queue
Got the message
KEY:queue VALUE:Value 3
Message received:Value 3
Waiting for a message in the queue


So, message queue would be another possible use case for Redis. There are some queues built on top of redis like RestMQ, Resque – a Job Queue and other.

I hope you enjoyed it.

See you in the next post.

Using an Embedded Tomcat with Maven tomcat plugin

When developing a java web application using the Eclipse WTP, we need to have an installation of tomcat in the machine in order to execute the application.

If you are using Maven on your project, you can use the tomcat plugin to run an embedded tomcat installation and test the application. It is very simple as you can see below.

OBS: To execute the steps given in this post you need to have installed in your eclipse the m2e plugin.

1. Create an Maven Project in eclipse, select the following maven archetype: maven-archetype-webapp
2. Insert the groupid and artifactid information

When you create a web project using this archetype, it already adds an index.jsp file.

Now we need to add the plugin information in the pom.xml as we can see below. In this example we are using the plugin for tomcat 7.x:


<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>br.com.xicojunior</groupId>
  <artifactId>test</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>teste Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
  <build>
    <finalName>test</finalName>
    <plugins>
	        <plugin>
	          <groupId>org.apache.tomcat.maven</groupId>
	          <artifactId>tomcat7-maven-plugin</artifactId>
	          <version>2.2</version>
	        </plugin>
	</plugins>
  </build>
</project>

The only change we made in the file was to add the section to add the tomcat 7 plugin.

After adding the plugin information, we can test it using the following maven goals:

clean install tomcat7:run

To execute those goals in eclipse:

1. Right Click in the project
2. Run as… -> Maven build…
3. Add the goals in the goals field
4. Click Run

Expect to see the following in the console:

[INFO] Running war on http://localhost:8080/test
[INFO] Creating Tomcat server configuration at C:\workspace\pessoal\redis\teste\target\tomcat
[INFO] create webapp with contextPath: /test
18/01/2014 17:43:53 org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-bio-8080"]
18/01/2014 17:43:53 org.apache.catalina.core.StandardService startInternal
INFO: Starting service Tomcat
18/01/2014 17:43:53 org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet Engine: Apache Tomcat/7.0.47
18/01/2014 17:43:54 org.apache.tomcat.websocket.server.WsSci onStartup
INFO: JSR 356 WebSocket (Java WebSocket 1.0) support is not available when running on Java 6. To suppress this message, run Tomcat on Java 7, remove the WebSocket JARs from $CATALINA_HOME/lib or add the WebSocketJARs to the tomcat.util.scan.DefaultJarScanner.jarsToSkip property in $CATALINA_BASE/conf/catalina.properties. Note that the deprecated Tomcat 7 WebSocket API will be available. 
18/01/2014 17:43:54 org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-bio-8080"]

Then we just need to test the given url in a browser, in my case:

http://localhost:8080/test

You can find more information and options in the plugin page.

That’s it for today.

See you in the next post.

Simple CRUD using Servlet 3.0, Redis/Jedis and CDI – Part 2

In this post we will focus on CDI and Servlet 3.0.
You can see part 1 here.

Let’s start with CDI.

When I started writing the post that originated this serie, I was not thinking in writing about CDI.
To be sincere I’ve never used that before. The idea of the post was to create a crud using jedis and servlets. But when I was writing the application I simply hated the idea to instantiate the beans.
In my daily job I use Spring for dependency injection and other stuff, but for this post I wouldn’t like to add it. So, I decided to try CDI and I was very surprised on how simple is to add and use it in the application.

So, what is CDI?

CDI is the acronym for Context and Dependency Injection, is the javaee specification to address DI on javaee platform.

So, once it is activated in your project you can easily inject a dependency by using the @Inject annotation. On CDI everything is a bean,
and almost all classes can be injected.

How to activate CDI?

If we are running our app in a Java EE application server, we need only to add an empty beans.xml in our META-INF folder. But in servers like tomcat, we need to add some more files and configurations:

1. Add weld-servlet.jar in the lib folder. You can get it from the Weld website;
2. Create a file context.xml under META-INF:

<?xml version="1.0" encoding="UTF-8"?>
<Context>
<Manager pathname=""/> <!-- disables storage of sessions across restarts -->
<Resource name="BeanManager"
auth="Container"
type="javax.enterprise.inject.spi.BeanManager"
factory="org.jboss.weld.resources.ManagerObjectFactory"/>
</Context>

3. Add some weld configurations on web.xml:

	<listener>
		<listener-class>org.jboss.weld.environment.servlet.Listener</listener-class>
	</listener>

	<resource-env-ref>
		<resource-env-ref-name>BeanManager</resource-env-ref-name>
			<resource-env-ref-type>
				javax.enterprise.inject.spi.BeanManager
			</resource-env-ref-type>
	</resource-env-ref>

4. Then we need only to add an empty beans.xml on META-INF or WEB-INF.

After that we are ready to start coding with CDI.

In the last post we created a UserDAO class, in the methods we used a instance of Jedis class to perform Redis commands. This instance was injected into UserDAO object by using the @Inject annotation. We can see that below:

public class UserDAO {


	@Inject Jedis jedis;
        //....
}

As we can see, it is so simple to inject an instance of Jedis class. If the Jedis class had a constructor with no argument it would be injected directly. But it doesn’t, so we used a class with a method annotated with @Produces. This indicates that this is a producer method. In our example we also used a JedisPool where we get the Jedis connections from. In this case we have two producers:

1. For the JedisPool
2. Other for Jedis connection. The Jedis producer has an instance of the JedisPool injected via @Inject, we can see them below:

JedisPoolFactory:



public class JedisPoolFactory {

	private String host = "localhost";
	private JedisPool jedisPool;
	@Singleton
	public @Produces JedisPool getJedisPool(){
		jedisPool = new JedisPool(new JedisPoolConfig(), host);
		return jedisPool;
	}

	public void detroy(@Disposes JedisPool jedisPool){
		jedisPool.destroy();
	}
}

In the code we see that the method getJedisPool is annotated with @Produces, saying it is a producer of JedisPool instances. In this code we see also two other annotations.
1. @Singleton- saying the returned instance is a singleton, that means there will be only one instance of this class;
2. @Disposes – Indicating which method should be called when destroying a instance of JedisPool;

Now we can see the JedisConnectionFactory:


public class JedisConnectionFactory {

	@Inject
	private JedisPool jedisPool;

	@Produces 
	public Jedis getJedis(){
		return jedisPool.getResource();
	}

	public void returnResource(@Disposes Jedis jedis){
		System.out.println("Returning jedis Connection");
		jedisPool.returnResource(jedis);
	}


}

To get a Jedis instance the class needs a JedisPool instance. The JedisPool is injected via @Inject and it is created by the producer method we saw in the last code. It also has a @Disposes that simply returns the connection to the Pool.

So, this way we can inject the Jedis instance into the DAO. Then in the other classes we simply use the @Inject, as we can see in the Service and Servlet class:

//UserService
@RequestScoped
public class UserService {

	@Inject
	UserDAO userDAO;
//...
}

//Servlet - UserController
public class UserController extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@Inject UserService userService;
//...
}

In this example we can see how simple is to add and use CDI in the application.

Servlet 3.0

The main difference we have on new servlets is that we don’t need to declare them in the web.xml, now we can simply set the servlet settings by using annotations. In the servlet we built in our example we used the annotation to set the url mapping for our servlet. Who already have developed a servlet before knows that it is one of the configurations we need to add on web.xml. We can see it in the servlet below:

@WebServlet("/UserController")
public class UserController extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@Inject UserService userService;
//...

//.. doGet
//.. doPost

}

In the code above we are saying the servlet will respond to the /UserController path. With this annotation we can add more configurations like:

@WebServlet(value="/UserController", name="userServlet")

In the code above we declared the mapping and the servlet name. There are other annotations to simplify the usage of servlets api, like @WebInitParam, @WebListener, @WebFilter. We will not talk about them but you can find great resources about them. Also, since servlets 3.0 there is support for async processing.

That’s it for today. Any comments or suggestions are welcome.

You can find the source code here.

Simple CRUD using Servlet 3.0, Redis/Jedis and CDI – Part 1

In this post we will build a simple user crud. The data will be stored in Redis. To interact with Redis we will use Jedis library. CDI for Depedency Injection and Servlet 3.0 for the view.

Let’s start with the Redis/Jedis part.

You can find some overview on Redis and Jedis in these posts.

Let’s start with the User class, we can see that below:

public class User {

	private String firstName;

	private String lastName;

	private String email;

	private String gender;

	private long id;
}

Now let’s define the keys we will use to store the user information on Redis. In our example we will use three keys:

  • user:ids – That will be used to generate the user ids by using the INCR command.
  • user:all – A Redis List to store all user ids
  • user:<id>:data – There will be one key with this pattern for each user in the system. Those keys will be hashes;

When we are going to add a new user to the system, we will handle three keys, as we can see in the steps below:

  1. First we get a new user id by incrementing the user:ids key: INCR user:ids
  2. Then we add it to the user:all list:  lpush user:all returnedId
  3. And add the user information in its own hash: HMSET user:<returnedId>:data field value ..

We can see this code in action the method UserDAO.addUser:

public User addUser(User user){

		long userId = jedis.incr(Keys.USER_IDS.key());
		user.setId(userId);

		//Getting the Pipeline
		Pipeline pipeline = jedis.pipelined();
		//add to users list
		pipeline.lpush(Keys.USER_ALL.key(), String.valueOf(userId));
		//add to the hash

		pipeline.hmset(Keys.USER_DATA.formated(String.valueOf(userId)), BeanUtil.toMap(user));

		pipeline.sync();

		return user;
	}

Explainning the code above, firstly we get the new user id. The jedis variable is an attribute of the UserDAO class, it is an instance of Jedis class. To avoid three network callings to the redis server we use the concept of Pipeline, so, in one calling to the redis server we will add the user id in the user:all list and the user info in the user:<id>:data hash.

The commands performed by the pipeline instance will be performed in the redis server after the calling of pipeline.sync().

We created an util class to convert the user object in a Map<String, String> to be stored in the redis hash.

To see the user’s detail we have a method in the DAO to get the user, that we can see below:

	public User getUser(long userId){

		String userInfoKey = Keys.USER_DATA.formated(String.valueOf(userId));
		Map<String, String> properties = jedis.hgetAll(userInfoKey);
		return BeanUtil.populate(properties, new User());
	}

As we can see it is a simple method, basically we call the command HGETALL to retrieve all fields from a Hash. The Jedis api returns that as Map so we can simply fill the user properties from the Map.

To remove the user we created the method below:

	public boolean remove(long userId){
		String userInfoKey = Keys.USER_DATA.formated(String.valueOf(userId));
		Pipeline pipeline = jedis.pipelined();
		Response<Long> responseDel = pipeline.del(userInfoKey);
		Response<Long> responseLrem = pipeline.lrem(Keys.USER_ALL.key(), 0, String.valueOf(userId));
		pipeline.sync();
		return responseDel.get() > 0 && responseLrem.get() > 0;
	}

The method below we also use the concept of pipelining once we need to remove the Hash key and the user id from the user:all list. The LREM command removes the value from the list, the zero indicates to remove all occurrences of this value in the list. In this method we also use the returned values from the commands by using the Response objects returned by each command. We can only use those objects after calling the sync method.

The update method is very simple, we can see it below:

	public User update(User user){
		String userInfoKey = Keys.USER_DATA.formated(String.valueOf(user.getId()));
		jedis.hmset(userInfoKey ,BeanUtil.toMap(user));
		return user;
	}

It is just a calling of HMSET passing a Map with all user attributes to be updated in the redis hash.

To list the users we would need also to use pipeline. Redis doesn’t provide a HMGETALL command, so, to retrieve all users with one network connection we will do that via pipeline.
The list method can be seen below:

	public List<User> list(){
		List<User> users = new ArrayList<User>();
		//Get all user ids from the redis list using LRANGE
		List<String> allUserIds = jedis.lrange(Keys.USER_ALL.key(), 0, -1);
		if(allUserIds != null && !allUserIds.isEmpty()){
			List<Response<Map<String,String>>> responseList = new ArrayList<Response<Map<String,String>>>();
			
			Pipeline pipeline = jedis.pipelined();
			for(String userId : allUserIds){
				//call HGETALL for each user id
				responseList.add(pipeline.hgetAll(Keys.USER_DATA.formated(userId)));
			}
			pipeline.sync();
			//iterate over the pipelined results
			for(Response<Map<String, String>> properties : responseList){
				users.add(BeanUtil.populate(properties.get(), new User()));
			}
		}
		return users;
	}

In this method we first get all the user ids from the list user:all by using the command LRANGE.
After that we do a “HMGETALL” via pipeline, we call the HGETALL command for each user, then we build the user objects from the Map instances returned.

In this first post we saw how to interact with the redis server using the Jedis api to store and retrieve the user’s information. We saw the concept and use of Pipeline. In the next post, we will show how to use CDI for Dependency Injection and Servlet 3.0 for the view.

Using Redis Hash with Jedis

Redis Hashes are maps between string fields and string values, so they are the perfect data type to represent objects (eg: A User with a number of fields like name, surname, age, and so forth)

That is the definition we have on redis documentation.

So, lets start with a simple user class that could be seen below:

public class User {

private String username;
 private String email;
 private String password;
 private String firstName;
 private String lastName;
}

Using Jedis we are able to store an object of this class in Redis, let’s see an example:


public void insertUser(User user){
 Map<String, String> userProperties = new HashMap<String, String>();
 userProperties.put("username", user.getUsername());
 userProperties.put("firstName", user.getFirstName());
 userProperties.put("lastName", user.getLastName());
 userProperties.put("email", user.getEmail());
 userProperties.put("password", user.getPassword());

 jedis.hmset("user:" + user.getUsername(), userProperties);
 }

As we could see basically we need to create a map containing the fields for the hash, and then we could use the HMSET command that allow us to set more than one field on the set.

We can also set only one field on the hash using the command hset, follow an example:


public void updateEmail(User user){
	jedis.hset("user:" + user.getUsername(), "email", user.getEmail());
}

Now we need to retrieve the entire User object from the Redis Hash, we can use HMGET where we need to specify which fields we want to retrieve or
we can use the HGETALL that returns all fields for the given key. Below we can see an example of HGETALL:


	public User loadUser(String username){
		Map<String, String> properties = jedis.hgetAll("user:" + username);
		User user = new User();
		user.setUsername(username);
		user.setEmail(properties.get("email"));
		//fill all attributes

		return user;
	}

To avoid the repeated code to create the bean from the Map and to create the bean from the map, we can use some libraries like commons Bean Utils that have some utility classes for doing that job.

We can see an example below:

//Getting the map of properties
properties = BeanUtilsBean.getInstance().describe(object);

//Populating the bean from the Map
BeanUtilsBean.getInstance().populate(bean, properties);

There are other commands that we can use with hashes, you can see all them on the redis page.

See you in the next post.