RSS

Category Archives: Uncategorized

Chatting Through JActor

Abstract : Nearly 40 years ago Carl Hewitt, Peter Bishop and Richard Steiger introduced the actor model. Since then it has been built in some languages (such as Scala, Erlang, etc.) and has been implemented by several frameworks. One (of not so many) Java actor frameworks is the JActor framework – “a high-throughput Java Actor framework” (as described by its author Bill la Forge). In this post we are going to take a (brief) look at JActor framework by building a simple backbone for chatting (j)actors.

Goal : Build a simple chat application using JActor framework

Acknowledgement: My gratitude goes to the open source community and especially to:

Bill la Forge creator of JActor framework

Code : Project code can be found @ GitHub under Apache License, Version 2.0

Full post : Read more @ ingini.org

 
Leave a comment

Posted by on November 23, 2012 in JActor, Java, Uncategorized

 

Tags: , , , , , , , , , , ,

Nested field access with FEST Reflect

Abstract: For one reason or another it’s often needed to access fields which are nested (sometimes deeply nested) within other fields. Of course you can write the logic yourself or (from now on) you can simply use the light-weighted framework FEST Reflect v1.4 (compatible with Java 1.5 and above). This short blog will show you how.

Acknowledgement: My gratitude goes to the open source community and to the following people:
Joel Costigliola for his support and open mind
Jonathan Melly for inspiring the idea of accessing nested fields

Goal: Discover the nested field functionality coming with the new release of FEST Reflect.

The maven dependency for FEST Reflect is as follows:

  <dependency>
    <groupId>org.easytesting</groupId>
    <artifactId>fest-reflect</artifactId>
    <version>1.4</version>
  </dependency>

Example 1: Setting a 1st level nested field

For this example we are going to need a simple service to start with, let’s say BusinessService :

public class BusinessService {
    private final NotificationService notificationService;

    public BusinessService() {
      this.notificationService = new NotificationService();
    }

    public void doBusinessLogic() {
      // ...
      notificationService.notifySomeone();
    }
   
  }

Our BusinessService is doing some business logic and in the end is notifying someone by using the NotificationService:

public class NotificationService {
    private final Logger logger = new Logger();
    private final IClientStatusDao clientStatusDao;

    public NotificationService() {
      this.clientStatusDao = new ClientStatusDao();
    }

    public void notifySomeone() {
      // notification logic goes here
      logger.info("About to update client status");
      clientStatusDao.updateStatus("client notified");
    }
  }

Now, imagine that you have a strong desire to access the logger field member inside the notificationService instance variable of our mighty BusinessService (for example when doing some testing). The path to the logger is: businessService.notificationService.logger

Here is how (line 7) you can take advantage of FEST Reflect:

import static org.fest.reflect.core.Reflection.field;

public class SomeTestClass {
  public void someTestMethod(){
    //some pre-testing logic ...
    Logger loggerMock = Mockito.mock(Logger.class);
    field("notificationService.logger").ofType(Logger.class).in(businessService)//
      .set(loggerMock);
    //some testing logic ...
  }
}

Notice that I’ve specified only “notificationService.logger” as an argument of the org.fest.reflect.core.Reflection.field() method. That’s because we give the root (businessService) of the path as an argument of the in() method. Yes, you’ve guessed it, that’s why I call this example accessing 1st level nested field.

By the way you don’t need to be testing in order to use FEST Reflect there are other situation where you can profit from accessing nested fields.

Example 2: Getting a 2nd level nested generic type field

There is no limit at what level the field at which you are interested is located (as long as you type the correct path to it).
Let’s continue our example and explore the ClientStatusDao class:

public class ClientStatusDao implements IClientStatusDao {
    private final Session session;
    private final List<String> listOfNotifications = Arrays.asList("General Notification", "Greetings");

    public ClientStatusDao() {
      this.session = new SessionImpl();
    }

    public void updateStatus(String newStatus) {
      session.startTransaction();
      // here we can use somehow our list of notifications and update status
      session.stopTransaction();
    }
  }

This time we are going to access an instance variable with a bit more complex type, namely the listOfNotifications which is of a List<String> type. Here is the one and only line you need (assuming you’ve already imported the static field method member (or all static members) of org.fest.reflect.core.Reflection):

List<String> listOfNames = field("notificationService.clientStatusDao.listOfNames").ofType(new TypeRef<List<String>>() {}).in(businessService).get();

Well, that was all for now folks. Please, leave a comment if you would like to share your views,recommendations, use-cases or requests. If you would like to contribute you can do it via GitHub FEST Reflect (you can add your requests at GitHub FEST Project Issues).

P.S.
In case you are wondering what else you can do with FEST Reflect and how to play with field access don’t forget to check my previous post on how to decorate fields (yes, you can decorate nested fields as well).

 
1 Comment

Posted by on June 18, 2012 in Uncategorized

 

Decoration with FEST-Reflect 1.3

Yesterday (3rd of April, 2012) the FEST-Reflect 1.3 (part of FEST libraries) was published on maven central. Since this fact requires a celebration, I’ve prepared a short tutorial of the new field decorator functionality.

Add the following dependency in your pom.xml to take advantage of FEST-Reflect.

		<dependency>
			<groupId>org.easytesting</groupId>
			<artifactId>fest-reflect</artifactId>
			<version>1.3</version>
		</dependency>

Example 1: Using FEST-Reflect decorator for testing logging functionality

Let’s say we have a simple business service:

package org.honey.service.impl;

import org.honey.service.IBusinessService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class BusinessService implements IBusinessService {

  private final Logger logger = LoggerFactory.getLogger(this.getClass());

  /**
   * {@inheritDoc}
   */
  @Override
  public void doBusiness() {
    logger.info("Hi! This is a business service ...");
  }
}

Our goal would be to test that the logger field is called and still be able to see the printed message on our screen. With the help of FEST-Reflect we can pre-decorate or post-decorate the logger with another object implementing the org.slf4j.Logger (I’m going to use a mock object via Mockito). Here is the test:

package org.honey.service.impl;

import static org.fest.reflect.core.Reflection.field;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;

import org.honey.service.IBusinessService;
import org.junit.Test;
import org.slf4j.Logger;

public class TestBusinessService {

  @Test
  public void shouldCallLogger() {
    //GIVEN
    Logger loggerMock = mock(Logger.class);

    IBusinessService service = new BusinessService();

    field("logger").ofType(Logger.class).in(service).preDecorateWith(loggerMock);

    //WHEN
    service.doBusiness();

    //THEN
    verify(loggerMock, times(1)).info(eq("Hi! This is a business service ..."));
  }
}

With the above code, our loggerMock is going to be called first and then the actual logger. We can also post-decorate the targeted field (in which case the logger will be called first and then the loggerMock):

field("logger").ofType(Logger.class).in(service).postDecorateWith(loggerMock);

In fact we can have both pre-decoration and post-decoration:

field("logger").ofType(Logger.class).in(service)//
.preDecorateWith(loggerMock).postDecorateWith(loggerMock);

However, don’t forget to change the verification step (for the test to work) to:

verify(loggerMock, times(2)).info(eq("Hi! This is a business service ..."));

Example 2: Complex decoration

Now let’s take a look at what kind of arsenal we have for tackling some more complex scenarios:

Let’s upgrade our BusinessService implementation:

public class BusinessService implements IBusinessService {

  private final Logger logger = LoggerFactory.getLogger(this.getClass());

  private final INotificationService notificationService;

  public BusinessService() {
    this.notificationService = new INotificationService() {

      @Override
      public boolean notify(String recipient) {
        // some logic
        return false;
      }
    };
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public void doBusiness() {

    String recipient = "some@one.com";

    if (notificationService.notify(recipient)) {
      logger.info("Successfully notified {}", recipient);
    } else {
      logger.error("Could not notifiy {}", recipient);
    }

  }

}

So what happened? I’ve added an INotificationService interface and a simple implementation in the constructor of our BusinessService. As we can see the implementation of INotificationService.notify() always returns false, so we can expect that the else branch in the doBusiness() method is always taken. What if we want to change this behaviour but without changing the actual INotificationService.notify() implementation? Here is a test that does exactly that:

public class TestBusinessService {

  @Test
  public void shouldCallInfoLogger() {
    //GIVEN
    Logger loggerMock = mock(Logger.class);

    INotificationService notificationServiceMock = mock(INotificationService.class);
    when(notificationServiceMock.sendNotification(anyString())).thenReturn(true);

    IBusinessService service = new BusinessService();

    field("logger").ofType(Logger.class).in(service).postDecorateWith(loggerMock);

    field("notificationService").ofType(INotificationService.class) //
          .in(service).postDecorateWith(notificationServiceMock)//
          .returningDecoratorResult();

    //WHEN
    service.doBusiness();

    //THEN
    verify(loggerMock, times(1)).info(eq("Successfully notified {}"), eq("some@one.com"));
  }
}

Again, we can pre-decorate instead of post-decorate, or we can pre- and post-decorate. Here is how:

field("notificationService").ofType(INotificationService.class) //
.in(service).preDecorateWith(notificationServiceMock1)//
.returningDecoratorResult()// taking the result from notificationServiceMock1
.postDecorateWith(notificationServiceMock2);

Ok, but what if our notificationServiceMock throws an exception? Well, we can silence any RuntimeException like this:

field("notificationService").ofType(INotificationService.class) //
.in(service).postDecorateWith(notificationServiceMock).returningDecoratorResult()//
.ignoringDecoratorExceptions(); // ignores any RuntimeException

Or a specific exception like this:

field("notificationService").ofType(INotificationService.class) //
.in(service).postDecorateWith(notificationServiceMock).returningDecoratorResult()//
.ignoringDecoratorExceptionsOfType(MyCoolException.class); // ignores only MyCoolException
 
1 Comment

Posted by on April 4, 2012 in FEST-Reflect, Java, Uncategorized